如何计算经过的时间,从现在乔达时?

问题描述:

我需要计算从一个特定日期所经过的的时间到现在为止,并以相同的格式*上的问题,也就是显示它:

I need to calculate the time elapsed from one specific date till now and display it with the same format as * questions, i.e.:

15s ago
2min ago
2hours ago
2days ago
25th Dec 08

你知道如何与Java的 乔达时?是否有已经实现了它一个辅助方法在那里,或者我应该写自己的算法?

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?

要计算所用的时间与JodaTime,使用Period$c$c>.要格式化所需的人力重新presentation所用的时间,使用PeriodFormatter$c$c>您可以通过PeriodFormatterBuilder$c$c>.

To calculate the elapsed time with JodaTime, use Period. To format the elapsed time in the desired human representation, use PeriodFormatter which you can build by PeriodFormatterBuilder.

下面是一个开球例如:

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);

这版画现在


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.