How to calculate elapsed time from now with Joda
I need to calculate the time elapsed from one specific date till now and display it with the same format as StackOverflow questions, ie:
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, 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()
.appendSeconds().appendSuffix(" seconds agon")
.appendMinutes().appendSuffix(" minutes agon")
.appendHours().appendSuffix(" hours agon")
.appendDays().appendSuffix(" days agon")
.appendWeeks().appendSuffix(" weeks agon")
.appendMonths().appendSuffix(" months agon")
.appendYears().appendSuffix(" years agon")
.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.
Use PrettyTime for Simple Elapsed Time.
I tried HumanTime as @sfussenegger answered and using JodaTime's Period
but the easiest and cleanest method for human readable elapsed time that I found was the PrettyTime library.
Here's a couple of simple examples with input and output:
Five Minutes Ago
DateTime fiveMinutesAgo = DateTime.now().minusMinutes( 5 );
new PrettyTime().format( fiveMinutesAgo.toDate() );
// Outputs: "5 minutes ago"
Awhile Ago
DateTime birthday = new DateTime(1978, 3, 26, 12, 35, 0, 0);
new PrettyTime().format( birthday.toDate() );
// Outputs: "4 decades ago"
CAUTION: I've tried palying around with the library's more precise functionality, but it produces some odd results so use it with care.
JP
You can do this with a PeriodFormatter but you don't have to go to the effort of making your own PeriodFormatBuilder as in other answers. If it suits your case, you can just use the default formatter:
Period period = new Period(startDate, endDate);
System.out.println(PeriodFormat.getDefault().print(period))
(hat tip to this answer on a similar question, I'm cross-posting for discoverability)
链接地址: http://www.djcxy.com/p/18596.html上一篇: Java中减去两个日期
下一篇: 从现在开始,如何计算Joda的流逝时间