Java Program To Calculate Time Difference In Seconds
Chapter:
Date and Time
Last Updated:
20-09-2023 14:48:20 UTC
Program:
/* ............... START ............... */
import java.time.LocalDateTime;
import java.time.Duration;
public class TimeDifferenceInSeconds {
public static void main(String[] args) {
// Create two LocalDateTime objects representing two different times
LocalDateTime startTime = LocalDateTime.of(2023, 9, 20, 10, 0, 0); // Replace with your start time
LocalDateTime endTime = LocalDateTime.of(2023, 9, 20, 12, 30, 0); // Replace with your end time
// Calculate the time difference in seconds
Duration duration = Duration.between(startTime, endTime);
long secondsDifference = duration.getSeconds();
System.out.println("Time difference in seconds: " + secondsDifference + " seconds");
}
}
/* ............... END ............... */
Output
Time difference in seconds: 9000 seconds
In this example, the program calculates the time difference in seconds between
the start time and end time, which is 2 hours and 30 minutes, or 9000 seconds.
Notes:
-
First we create two LocalDateTime objects, startTime and endTime, representing the two different times for which we want to calculate the time difference.
- Then we use the Duration.between() method to calculate the duration between the two LocalDateTime objects. This method returns a Duration object.
- In next step we extract the number of seconds from the Duration object using the getSeconds() method and store it in the secondsDifference variable.
- Finally, we print the time difference in seconds.
- Replace the values of startTime and endTime with your desired date and time values to calculate the time difference between them in seconds.