Ankit Ostwal
Ankit Ostwal

Reputation: 1051

difference in seconds between two dates using joda time?

Suppose there are two dates A(start time) & B(end time). A & B could be the time on the same day or even different day. My task is to show difference in seconds. Date format which i am using is

Date Format :: "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 

For e.g.

start date ::   "2011-11-16T14:09:23.000+00:00"
end date ::     "2011-11-17T05:09:23.000+00:00"            

Help is appreciated.

Upvotes: 47

Views: 33291

Answers (2)

linqu
linqu

Reputation: 11970

The answer of @pcalcao will be best in most cases. Be aware that seconds will be rounded to an integer.

If you are interested in sub-seconds accuracy just substract the milliseconds:

double seconds = (now.getMillis() - dateTime.getMillis()) / 1000d;

Upvotes: 7

pcalcao
pcalcao

Reputation: 15965

Use the Seconds class:

DateTime now = DateTime.now();
DateTime dateTime = now.plusMinutes(10);
Seconds seconds = Seconds.secondsBetween(now, dateTime);
System.out.println(seconds.getSeconds());

This piece of code prints out 600. I think this is what you need.

As further advice, explore the documentation of joda-time. It's pretty good, and most things are very easy to discover.

In case you need some help with the parsing of dates (It's in the docs, really), check out the related questions, like this:

Parsing date with Joda with time zone

Upvotes: 113

Related Questions