Java Calculate Number of Seconds Between Two Calendar
Tags: Java Calendar TimeUnit DateUtil
In this Java tutorial, we learn how to calculate number seconds between two Calendar objects in Java programming language.
How to calculate number of seconds between two Calendar objects in Java
At this first step, we create a new Java utility class named DateUtil, and implement a new static method named getNumberOfSecondsBetween(Calendar start, Calendar end), this method follow these steps to calculate number of seconds between two Calendar objects.
- Step 1: calculate number of milliseconds between start and end Calendar objects.
- 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.Calendar;
import java.util.concurrent.TimeUnit;
public class DateUtil {
/**
* This method to get number of seconds between two Calendar objects.
* @param start the start Calendar object
* @param end the end Calendar object
* @return the number of seconds between start and end Calendar.
*/
public static long getNumberOfSecondsBetween(Calendar start, Calendar end) {
long numberOfMilliseconds = end.getTimeInMillis() - start.getTimeInMillis();
long numberOfSeconds = TimeUnit.SECONDS.convert(numberOfMilliseconds, TimeUnit.MILLISECONDS);
return numberOfSeconds;
}
}
In the following example Java code, we learn how to use the above getNumberOfSecondsBetween(Calendar start, Calendar end) static method to calculate number of seconds between two Calendar objects in Java program.
NumberOfSecondsBetweenCalendarExample.java
import java.util.Calendar;
import java.util.GregorianCalendar;
public class NumberOfSecondsBetweenCalendarExample {
public static void main(String... args) {
Calendar start = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 10, 0);
Calendar end = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 11, 0);
// Calculate Number of Seconds Between Two Calendar objects
long numberOfSeconds = DateUtil.getNumberOfSecondsBetween(start, end);
System.out.println("Start Date: " + start.getTime());
System.out.println("End Date: " + end.getTime());
System.out.println("Number of seconds: " + numberOfSeconds);
}
}
Start Date: Fri Jul 01 08:10:00 ICT 2022
End Date: Fri Jul 01 08:11:00 ICT 2022
Number of seconds: 60
Happy Coding 😊
Related Articles
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 Milliseconds Between Two Calendar
Java Calculate Number of Days Between Two Date
Java Calculate Number of Hours Between Two Date
Java Calculate Number of Minutes Between Two Date