Seconds between two dates

This example shows how to find the number of seconds between two dates using Java 8 date time api and Joda time. We will set the start date by subtracting 1 day from the current date and the end date to today. Then we will find the number of seconds between the start date and end date which equates to 86400 seconds.

Java 8 Date and Time API

This snippet will find the difference between two dates in seconds using java 8 Duration.between and ChronoUnit.SECONDS.between. Both approaches will calculate the amount of time between two temporal objects in the form of seconds.

@Test
public void seconds_between_two_dates_in_java_with_java8 () {

    LocalDateTime startDate = LocalDateTime.now().minusDays(1);
    LocalDateTime endDate = LocalDateTime.now();

    long secondsInDay = Duration.between(startDate, endDate).toMinutes();
    assertEquals(1440, secondsInDay);

    // or

    long secondsInDay2 = ChronoUnit.SECONDS.between(startDate, endDate);
    assertEquals(86400, secondsInDay2);
}

Joda Time

Using joda, this snippet will calculate number of seconds between two dates using Seconds.secondsBetween.

@Test
public void seconds_between_two_dates_in_java_with_joda () {

    // start day is 1 day in the past
    DateTime startDate = new DateTime().minusDays(1);
    DateTime endDate = new DateTime();

    Seconds seconds = Seconds.secondsBetween(startDate, endDate);

    int secondsInDay = seconds.getSeconds();

    assertEquals(86400, secondsInDay);
}