本文介绍了如何计算经过的时间,从现在乔达时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

你知道如何与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,使用<$c$c>Period.要格式化所需的人力重新presentation所用的时间,使用<$c$c>PeriodFormatter您可以通过<$c$c>PeriodFormatterBuilder.

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

你看,我已经花费数月甚至几年考虑以及和其配置为省略值时,这些都为零。

You see that I've taken months and years into account as well and configured it to omit the values when those are zero.

这篇关于如何计算经过的时间,从现在乔达时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:12