91

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?

snakile
  • 52,936
  • 62
  • 169
  • 241

13 Answers13

203

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

Scott Stanchfield
  • 29,742
  • 9
  • 47
  • 65
34

I should like to provide the modern answer. The other answers were fine when this question was asked, but time moves on. Today I recommend you use java.time, the modern Java date and time API.

    ZonedDateTime aDateTime = ZonedDateTime.of(2017, 12, 8, 19, 25, 48, 991000000, ZoneId.of("Europe/Sarajevo"));
    ZonedDateTime otherDateTime = ZonedDateTime.of(2017, 12, 8, 20, 10, 38, 238000000, ZoneId.of("Europe/Sarajevo"));

    long diff = ChronoUnit.SECONDS.between(aDateTime, otherDateTime);
    System.out.println("Difference: " + diff + " seconds");

This prints:

Difference: 2689 seconds

ChronoUnit.SECONDS.between() works with two ZonedDateTime objects or two OffsetDateTimes, two LocalDateTimes, etc.

If you need anything else than just the seconds, you should consider using the Duration class:

    Duration dur = Duration.between(aDateTime, otherDateTime);
    System.out.println("Duration: " + dur);
    System.out.println("Difference: " + dur.getSeconds() + " seconds");

This prints:

Duration: PT44M49.247S
Difference: 2689 seconds

The former of the two lines prints the duration in ISO 8601 format, the output means a duration of 44 minutes and 49.247 seconds.

Why java.time?

The Date class used in several of the other answers is now long outdated. Joda-Time also used in a couple (and possibly in the question) is now in maintenance mode, no major enhancements are planned, and the developers officially recommend migrating to java.time, also known as JSR-310.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 3
    Very underrated answer. Jodatime's calculations here are a little messy. However `ChronoUnit.SECONDS.between(oldDate.toInstant(), newDate.toInstant())` is rather easy to remember. – fIwJlxSzApHEZIl Apr 04 '18 at 22:51
10

You should do

org.joda.time.Seconds.secondBetween(date1, date2)
7

That should do it:

Date a = ...;
Date b = ...;

Math.abs(a.getTime()-b.getTime())/1000;

Here the relevant documentation: Date.getTime(). Be aware that this will only work for dates after January 1, 1970, 00:00:00 GMT

Johannes Weiss
  • 52,533
  • 16
  • 102
  • 136
  • Hmm, why would this only work for dates after Jan 1, 1970? Before that the values are negative, but arithmetic works on negative numbers. – Jay Dec 28 '09 at 17:24
6

You can use org.apache.commons.lang.time.DateUtils to make it cleaner:

(firstDate.getTime() - secondDate.getTime()) / DateUtils.MILLIS_PER_SECOND
shem
  • 4,686
  • 2
  • 32
  • 43
5

There is no such class as DateTime in the standard Java SE API. Although there is one in joda-time, even that does not have a daysBetween method.

Using the standard Java API, the easiest way to get seconds between two java.util.Date objects would be to subtract their timestamps and divide by 1000:

int secondsBetween = (date1.getTime() - date2.getTime()) / 1000;
andri
  • 11,171
  • 2
  • 38
  • 49
5

It is not recommended to use java.util.Date or System.currentTimeMillis() to measure elapsed times. These dates are not guaranteed to be monotonic and will changes occur when the system clock is modified (eg when corrected from server). In probability this will happen rarely, but why not code a better solution rather than worrying about possibly negative or very large changes?

Instead I would recommend using System.nanoTime().

long t1 = System.nanoTime();
long t2 = System.nanoTime();

long elapsedTimeInSeconds = (t2 - t1) / 1000000000;

EDIT

For more information about monoticity see the answer to a related question I asked, where possible nanoTime uses a monotonic clock. I have tested but only using Windows XP, Java 1.6 and modifying the clock whereby nanoTime was monotonic and currentTimeMillis wasn't.

Also from Java's Real time doc's:

Q: 50. Is the time returned via the real-time clock of better resolution than that returned by System.nanoTime()?

The real-time clock and System.nanoTime() are both based on the same system call and thus the same clock.

With Java RTS, all time-based APIs (for example, Timers, Periodic Threads, Deadline Monitoring, and so forth) are based on the high-resolution timer. And, together with real-time priorities, they can ensure that the appropriate code will be executed at the right time for real-time constraints. In contrast, ordinary Java SE APIs offer just a few methods capable of handling high-resolution times, with no guarantee of execution at a given time. Using System.nanoTime() between various points in the code to perform elapsed time measurements should always be accurate.

Community
  • 1
  • 1
Pool
  • 11,999
  • 14
  • 68
  • 78
  • Hmm, interesting post. What makes you say that nanoTime is not subject to clock updates? I don't see anything in the Java documentation about this. I'm not saying you're wrong, I'm must wondering if you have a reference or have performed experiments to back this up. – Jay Dec 28 '09 at 17:26
4

If you're using Joda (which may be coming as jsr 310 in JDK 7, separate open source api until then) then there is a Seconds class with a secondsBetween method.

Here's the javadoc link: http://joda-time.sourceforge.net/api-release/org/joda/time/Seconds.html#secondsBetween(org.joda.time.ReadableInstant,%20org.joda.time.ReadableInstant)

cserepj
  • 926
  • 6
  • 9
1

For java 8+ you can use

ChronoUnit.SECONDS.between(temporal1,temporal2)

Andrew Taran
  • 71
  • 1
  • 4
0

Which class ? Do you mean the Joda DateTime class ? If so, you can simply call getMillis() on each, and perform the appropriate subtraction/scaling.

I would recommend Joda for date/time work, btw, due to it's useful and intuitive API, and its thread-safety for formatting/parsing options.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

Just a pointer: If you're calculating the difference between two java.util.Date the approach of subtracting both dates and dividing it by 1000 is reasonable, but take special care if you get your java.util.Date reference from a Calendar object. If you do so, you need to take account of daylight savings of your TimeZone since one of the dates you're using might take place on a DST period.

That is explained on Prasoon's link, I recommend taking some time to read it.

Fabio Kenji
  • 776
  • 1
  • 7
  • 17
0

Use this method:

private Long secondsBetween(Date first, Date second){
    return (second.getTime() - first.getTime())/1000;
}
Mattew Eon
  • 1,722
  • 1
  • 21
  • 38
Mauro Midolo
  • 1,841
  • 3
  • 14
  • 34
  • 2
    Add some explanation to your answer please. – Alex Char Apr 16 '15 at 14:22
  • Its clear that you need to send two Dates, i mean, Date initialDate = new Date() and Date finalDate = new Date() so if you send initialDate and finalDate you can get the difference in secods... both of them will be "convertt" to Long with the method getTIme and finally you will get the difference divided by 1000 to get the seconds... great answer by the way! – Raul Guerrero Nov 16 '20 at 02:16
0

Use time unit class.

long timeDifferentInSeconds = TimeUnit.MILLISECONDS.toSeconds(currentDate.getTime()) - TimeUnit.MILLISECONDS.toSeconds(previousDate.getTime());
Abdullah Ismail
  • 415
  • 5
  • 6