如何在 Java 中计算时间跨度并格式化输出? [英] How can I calculate a time span in Java and format the output?
问题描述
我想取两次(自纪元以来的秒数)并以如下格式显示两者之间的差异:
- 2 分钟
- 1 小时 15 分钟
- 3 小时 9 分钟
- 1 分钟前
- 1 小时 2 分钟前
我怎样才能做到这一点??
既然大家都喊YOODAA!!!"但没有人发布一个具体的例子,这是我的贡献.
您也可以使用 Joda-Time 执行此操作.使用 Period
代表一个时期.要在所需的人类表示中格式化句点,请使用 PeriodFormatter
您可以通过 PeriodFormatterBuilder
.
这是一个启动示例:
DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);DateTime now = new DateTime();期间期间=新期间(myBirthDate,现在);PeriodFormatter 格式化程序 = new PeriodFormatterBuilder().appendYears().appendSuffix("年,","年,").appendMonths().appendSuffix("月,","月,").appendWeeks().appendSuffix("周,","周,").appendDays().appendSuffix(" day, ", " days, ").appendHours().appendSuffix("小时,","小时,").appendMinutes().appendSuffix("minute,","minutes,").appendSeconds().appendSuffix("秒","秒").printZeroNever().toFormatter();String elapsed = formatter.print(period);System.out.println(elapsed + " ago");
更加简洁明了,不是吗?
现在打印出来
<前>32年1个月1周5天6小时56分24秒前(咳,老,咳)
I want to take two times (in seconds since epoch) and show the difference between the two in formats like:
- 2 minutes
- 1 hour, 15 minutes
- 3 hours, 9 minutes
- 1 minute ago
- 1 hour, 2 minutes ago
How can I accomplish this??
Since everyone shouts "YOODAA!!!" but noone posts a concrete example, here's my contribution.
You could also do this with Joda-Time. Use Period
to represent a period. To format the period in the desired human representation, use PeriodFormatter
which you can build by PeriodFormatterBuilder
.
Here's a kickoff example:
DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" year, ", " years, ")
.appendMonths().appendSuffix(" month, ", " months, ")
.appendWeeks().appendSuffix(" week, ", " weeks, ")
.appendDays().appendSuffix(" day, ", " days, ")
.appendHours().appendSuffix(" hour, ", " hours, ")
.appendMinutes().appendSuffix(" minute, ", " minutes, ")
.appendSeconds().appendSuffix(" second", " seconds")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed + " ago");
Much more clear and concise, isn't it?
This prints by now
32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago
(Cough, old, cough)
这篇关于如何在 Java 中计算时间跨度并格式化输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!