Since everyone shouts "YOODAA!!!" but noone posts a concrete example, here's my contribution.
You could also do this with Joda-Time. Use Period
to represent a period. To format the period 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()
.appendYears().appendSuffix(" year, ", " years, ")
.appendMonths().appendSuffix(" month, ", " months, ")
.appendWeeks().appendSuffix(" week, ", " weeks, ")
.appendDays().appendSuffix(" day, ", " days, ")
.appendHours().appendSuffix(" hour, ", " hours, ")
.appendMinutes().appendSuffix(" minute, ", " minutes, ")
.appendSeconds().appendSuffix(" second", " seconds")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed + " ago");
Much more clear and concise, isn't it?
This prints by now
32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago
(Cough, old, cough)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…