Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference in seconds between two dates using joda time?

Tags:

java

jodatime

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.

like image 406
Ankit Ostwal Avatar asked Feb 28 '13 11:02

Ankit Ostwal


People also ask

How do you find the difference in seconds between two dates?

To get the number of seconds between 2 dates: Get the number of milliseconds between the unix epoch and the Dates. Subtract the milliseconds of the start date from the milliseconds of the end date. Divide the result by the number of milliseconds in a second (1000).

How can you find out the difference between two dates in Java?

getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates. It returns the years, days, hours, minutes, and seconds between the two specifies dates.

How do I find the difference between two dates in seconds in Swift?

Date Difference Extension in Swiftlet formatter = DateFormatter() formatter. dateFormat = "yyyy/MM/dd HH:mm" let xmas = formatter. date(from: "2021/12/24 00:00") let newYear = formatter. date(from: "2022/01/01 00:00") print(newYear!

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.


2 Answers

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

like image 111
pcalcao Avatar answered Sep 29 '22 14:09

pcalcao


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; 
like image 31
linqu Avatar answered Sep 29 '22 16:09

linqu