Java Program to Calculate Difference Between Two Time Periods
Last Updated :
11 Dec, 2020
In this article, let’s explore the various methods to find the difference between the Two Time Periods in Java. For simplicity, let’s assume that the Time Period provided to us is in the format HH:MM:SS
Example
Input : 1st Time Period :- 18:00:00
2nd Time Period :- 21:00:00
Output: 3 hours 0 minutes and 0 seconds
Input : 1st Time Period :- 17:00:00
2nd Time Period :- 23:22:00
Output: 6 hours 22 minutes and 0 seconds
Method 1 :- Using SimpleDateFormat class and Date class
SimpleDateFormat class has been added to the java.text package in the 7th JDK version. Parse the Time Period in the format HH:MM:SS by creating a SimpleDateFormat object. SimpleDateFormat object parses the Time period and returns a Date object which can be used to calculate the time elapsed.
Below is the code for the above approach:
Java
import java.util.*;
import java.text.*;
public class GFG {
public static void main(String[] args) throws Exception
{
String time1 = "18:00:00" ;
String time2 = "7:30:50" ;
SimpleDateFormat simpleDateFormat
= new SimpleDateFormat( "HH:mm:ss" );
Date date1 = simpleDateFormat.parse(time1);
Date date2 = simpleDateFormat.parse(time2);
long differenceInMilliSeconds
= Math.abs(date2.getTime() - date1.getTime());
long differenceInHours
= (differenceInMilliSeconds / ( 60 * 60 * 1000 ))
% 24 ;
long differenceInMinutes
= (differenceInMilliSeconds / ( 60 * 1000 )) % 60 ;
long differenceInSeconds
= (differenceInMilliSeconds / 1000 ) % 60 ;
System.out.println(
"Difference is " + differenceInHours + " hours "
+ differenceInMinutes + " minutes "
+ differenceInSeconds + " Seconds. " );
}
}
|
Output
Difference is 10 hours 29 minutes 10 Seconds.
Time Complexity: O(1)
Method 2 :- Using the LocalTime and ChronoUnit class
Java has brought a ton of features in the 8th JDK version and few of them are the LocalTime and ChronoUnit classes present in the java.time package. LocalTime object parses the date in the format HH:MM:SS and ChronoUnit is used to get the difference in hours, minutes and seconds.
Below is the code for the above approach:
Java
import java.time.*;
import java.time.temporal.ChronoUnit;
class GFG {
public static void main(String[] args)
{
LocalTime time1 = LocalTime.of( 18 , 00 , 00 );
LocalTime time2 = LocalTime.of( 21 , 22 , 00 );
long hours = ChronoUnit.HOURS.between(time1, time2);
long minutes
= ChronoUnit.MINUTES.between(time1, time2) % 60 ;
long seconds
= ChronoUnit.SECONDS.between(time1, time2) % 60 ;
System.out.println(
"Difference is " + hours + " hours " + minutes
+ " minutes " + seconds + " seconds." );
}
}
|
Output
Difference is 3 hours 22 minutes 0 seconds.
Time Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...