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 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.
java.util.Date
only. However, my lib Time4J is IMHO the best lib for printing either relative times (ago-format) or times in format like "3 months, 4 days". It is also localizable for actually 72 languages. – Biplane