Java Time Difference

Time difference can be calculated by subtracting the milliseconds. And then milliseconds can be converted into different Units using TimeUnit.

e.g.

TimeUnit.MILLISECONDS.toSeconds(1000)

will give 1 because 1 second equivalent to 1000 millisecons.

Following sample gives a example of finding difference between two dates and converting them into different units

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TimeDifference {
    public static void main(String[] args) {
        Date date1 = new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000));
        Date date2 = new Date();

        long timeDifferenceInDays = TimeUnit.MILLISECONDS.toDays(date2.getTime() - date1.getTime());
        long timeDifferenceInHours = TimeUnit.MILLISECONDS.toHours(date2.getTime() - date1.getTime());
        long timeDifferenceInMinutes = TimeUnit.MILLISECONDS.toMinutes(date2.getTime() - date1.getTime());
        long timeDifferenceInSeconds = TimeUnit.MILLISECONDS.toSeconds(date2.getTime() - date1.getTime());
        long timeDifferenceInMirco = TimeUnit.MILLISECONDS.toMicros(date2.getTime() - date1.getTime());
        long timeDifferenceInNanos = TimeUnit.MILLISECONDS.toNanos(date2.getTime() - date1.getTime());

        System.out.println("timeDifferenceInDays: " + timeDifferenceInDays);
        System.out.println("timeDifferenceInHours: " + timeDifferenceInHours);
        System.out.println("timeDifferenceInMinutes: " + timeDifferenceInMinutes);
        System.out.println("timeDifferenceInSeconds: " + timeDifferenceInSeconds);
        System.out.println("timeDifferenceInMirco: " + timeDifferenceInMirco);
        System.out.println("timeDifferenceInNanos: " + timeDifferenceInNanos);
    }
}

Output:

timeDifferenceInDays: 1
timeDifferenceInHours: 24
timeDifferenceInMinutes: 1440
timeDifferenceInSeconds: 86400
timeDifferenceInMirco: 86400000000
timeDifferenceInNanos: 86400000000000

Duration

The duration between two dates can be calculated using Duration object:

e.g. If you want to log something after 15 mins of last log then

import java.time.Duration;
import java.time.Instant;
...
if (Duration.between(lastLog, Instant.now()).toMinutes() > 15) {
    // your code
    ...
    lastLog = Instant.now();
}

or

import java.util.concurrent.TimeUnit;
...
if (TimeUnit.MILLISECONDS.toMinutes(lastLog - System.currentTimeMillis()) > 15) {
    // your code
    ...
    lastLog = System.currentTimeMillis();
}

Note:

  • To convert date to instant use toInstant() in Date object e.g. Instant instant = new Date().toInstant();
  • To convert instant to Date use from() in Date e.g. Date date = Date.from(instant);