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, usePeriodFormatterwhich you can build byPeriodFormatterBuilder.Here’s a kickoff example:
This prints by now
(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.