如何用Joda-Time计算从现在开始的时间? [英] How to calculate elapsed time from now with Joda-Time?
问题描述
我需要计算从特定日期到现在的时间,并显示与StackOverflow问题相同的格式,例如:
15s ago
pre>
2分钟前
2小时前
2天前
25th Dec 08
您是否知道如何使用Java Joda-Time 库?有没有一个帮助方法已经实现了,或者我应该自己编写算法?
解决方案计算经过的时间与JodaTime,使用
期间
。要以所需的人类表示格式化经过的时间,请使用PeriodFormatter
,您可以通过PeriodFormatterBuilder
。
这是一个开球例如:
DateTime myBirthDate = new DateTime(1978,3,26,12,35,0,0);
DateTime now = new DateTime();
期间=新的期间(myBirthDate,现在);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendSeconds()。appendSuffix(seconds ago\\\
)
.appendMinutes()。appendSuffix(分钟前\\ n)
.appendHours()。appendSuffix(hours ago\\\
)
.appendDays()。appendSuffix(days ago\\\
)
.appendWeeks()。 appendSuffix(weeks ago\\\
)
.appendMonths()。appendSuffix(months ago\\\
)
.appendYears()。appendSuffix(years ago\\\
)
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(已过);
现在打印
3秒前
51分钟前
7小时前
6天前
10个月前
31年前
$ (咳嗽,老,咳嗽) 你看,我已经考虑了几个月和几年了并将其配置为在零时为零省略。I need to calculate the time elapsed from one specific date till now and display it with the same format as StackOverflow questions, i.e.:
15s ago 2min ago 2hours ago 2days ago 25th Dec 08
Do you know how to achieve it with the Java Joda-Time library? Is there a helper method out there that already implements it, or should I write the algorithm myself?
解决方案To calculate the elapsed time with JodaTime, use
Period
. To format the elapsed time in the desired human representation, usePeriodFormatter
which you can build byPeriodFormatterBuilder
.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() .appendSeconds().appendSuffix(" seconds ago\n") .appendMinutes().appendSuffix(" minutes ago\n") .appendHours().appendSuffix(" hours ago\n") .appendDays().appendSuffix(" days ago\n") .appendWeeks().appendSuffix(" weeks ago\n") .appendMonths().appendSuffix(" months ago\n") .appendYears().appendSuffix(" years ago\n") .printZeroNever() .toFormatter(); String elapsed = formatter.print(period); System.out.println(elapsed);
This prints by now
3 seconds ago 51 minutes ago 7 hours ago 6 days ago 10 months ago 31 years ago(Cough, old, cough) You see that I've taken months and years into account as well and configured it to omit the values when those are zero.
这篇关于如何用Joda-Time计算从现在开始的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!