Java Calculate Number of Seconds Between Two Date

Tags: Java Date TimeUnit DateUtil

In this Java tutorial, we learn how to calculate the number of seconds between two Date objects in Java programming language.

How to calculate number of seconds between two Date objects in Java

In this first step, we create a new Java class named DateUtil, and implement a new static method named getNumberOfSecondsBetween(Date start, Date end), this new method follow these steps to calculate number of seconds between two Date values.

  • Step 1: calculate number of milliseconds between start and end Date values.
  • Step 2: convert number of milliseconds into number of seconds using the TimeUnit.SECONDS.convert(long sourceDuration, TimeUnit sourceUnit) method.

DateUtil.java

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

public class DateUtil {

    /**
     * This method to get number of seconds between two Date objects.
     * @param start the start Date object
     * @param end the end Date object
     * @return the number of seconds between start and end Date.
     */
    public static long getNumberOfSecondsBetween(Date start, Date end) {
        long numberOfMilliseconds = end.getTime() - start.getTime();
        long numberOfSeconds = TimeUnit.SECONDS.convert(numberOfMilliseconds, TimeUnit.MILLISECONDS);
        return numberOfSeconds;
    }

}

In the following example Java code, we learn how to use the above DateUtil class to calculate number of seconds between two Date objects in Java program.

NumberOfSecondsBetweenDateExample.java

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class NumberOfSecondsBetweenDateExample {
    public static void main(String... args) {
        Date startDate = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 30, 0).getTime();
        Date endDate = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 31, 0).getTime();

        // Calculate Number of Seconds Between Two Date objects
        long numberOfSeconds = DateUtil.getNumberOfSecondsBetween(startDate, endDate);

        System.out.println("Start Date: " + startDate);
        System.out.println("End Date: " + endDate);
        System.out.println("Number of seconds: " + numberOfSeconds);
    }
}
The output as below.
Start Date: Fri Jul 01 08:30:00 ICT 2022
End Date: Fri Jul 01 08:31:00 ICT 2022
Number of seconds: 60

Happy Coding 😊

Java Calculate Number of Days Between Two Date

Java Calculate Number of Hours Between Two Date

Java Calculate Number of Minutes Between Two Date

Java Calculate Number of Milliseconds Between Two Date

Java Calculate Number of Days Between Two Calendar

Java Calculate Number of Hours Between Two Calendar

Java Calculate Number of Minutes Between Two Calendar

Java Calculate Number of Seconds Between Two Calendar

Java Calculate Number of Milliseconds Between Two Calendar