Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate elapsed time from now with Joda-Time?

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?

like image 465
fabien7474 Avatar asked Feb 01 '10 19:02

fabien7474


People also ask

What is Joda-Time?

Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.

Is Joda-Time deprecated?

So the short answer to your question is: YES (deprecated).

Does Joda datetime have timezone?

An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.

How do I import Joda-time?

Copy (or) drag & drop the joda-time-2.1. jar into the newly created libs folder. Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1. jar .


1 Answers

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.

like image 172
BalusC Avatar answered Oct 28 '22 02:10

BalusC