当 x 超过 3600 秒时,有没有办法将 'x' 秒转换为 y 小时和 z 秒?同样,当x超过60但小于3600秒时,使用JodaTime?将其转换为'a分b秒'。我知道我必须在 periodFormatter 中指定我需要的内容,但我不想指定它 - 我想要一个基于秒值的格式化文本。
这类似于您在论坛上发帖的方式,然后您的帖子最初会显示为“10 秒前发布”。1 分钟后,您会看到“1 分钟 20 秒前发布”,几周、几天也是如此,年。
最佳答案
我不确定您为什么不想在 PeriodFormatter
中指定您需要的内容。 JodaTime
不知道如何将句点显示为字符串,因此您需要通过 PeriodFormatter
告诉它。
由于 3600 秒等于 1 小时,正确使用格式化程序会自动为您完成此操作。下面是一个代码示例,在同一格式化程序上使用多个不同的输入,应该可以实现您想要的结果。
Seconds s1 = Seconds.seconds(3601);
Seconds s2 = Seconds.seconds(2000);
Seconds s3 = Seconds.seconds(898298);
Period p1 = new Period(s1);
Period p2 = new Period(s2);
Period p3 = new Period(s3);
PeriodFormatter dhm = new PeriodFormatterBuilder()
.appendDays()
.appendSuffix(" day", " days")
.appendSeparator(" and ")
.appendHours()
.appendSuffix(" hour", " hours")
.appendSeparator(" and ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(" and ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
System.out.println(dhm.print(p1.normalizedStandard()));
System.out.println(dhm.print(p2.normalizedStandard()));
System.out.println(dhm.print(p3.normalizedStandard()));
产生输出::
1 hour and 1 second
33 minutes and 20 seconds
3 days and 9 hours and 31 minutes and 38 seconds
关于java - 使用 JodaTime 自动将秒转换为年/日/小时/分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891762/