Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how do I get the difference in seconds between 2 dates?

The Java class library has a class named DateTime. DateTime has this method:

int daysBetween(DateTime other) 

which returns the number of days between this and the parameter. It doesn't have a method

int secondsBetween(DateTime other) 

which I happen to need. Is there a class which is similar to DateTime but has such a method?

like image 285
snakile Avatar asked Dec 28 '09 16:12

snakile


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 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 you find the time difference between two timestamps in seconds?

If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.

Which method finds the difference in days between two dates?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.


1 Answers

Not familiar with DateTime...

If you have two Dates you can call getTime on them to get millseconds, get the diff and divide by 1000. For example

Date d1 = ...; Date d2 = ...; long seconds = (d2.getTime()-d1.getTime())/1000; 

If you have Calendar objects you can call

c.getTimeInMillis() 

and do the same

like image 147
Scott Stanchfield Avatar answered Sep 22 '22 11:09

Scott Stanchfield