How to calculate time difference in Java
In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example.
Prerequisite
To understand this example, you need to be familiar with the following Java programming concepts:
- Java Methods: A method is a piece of code that accomplishes a certain job. Assume you need to make a program that will make a circle and colour it. To overcome this difficulty, you can devise two approaches:
- a technique for drawing a circle
- a technique for colouring the circle
By breaking down a complex problem into smaller bits, you can create a program that is easier to comprehend and reuse. There are two sorts of approaches in Java: - User-defined Methods: Based on our needs, we can develop our approach.
- Standard Library Methods: These are Java's built-in techniques that can be used.
- Java Objects and Classes: Java is a language that supports the principle of object-oriented programs. The object-oriented approach's main notion is to decompose large issues into little objects. Any entity with a state and behaviour is referred to as an object. A bicycle, for example, is an object. It has
- Idle, first gear, and so on are an example of states.
- Braking, acceleration, and other actions are examples of behaviours.
Let's start with classes in Java before moving on to objects.
Java Classes
A class is an object's template. We must first declare the class before we can construct an object.
The class can be compared to a sketch (prototype) of a home. It includes information about the doors, floors, and windows, among other elements. On the basis of all these descriptions, we build the house.The object is a house. Because various houses can be made from the same description, we can make various objects from a class.
Java Objects
An example of a class is an object that belongs to that class. Assuming Bicycle is a class, and then Sports Bicycle, Mountain Bicycle, Touring Bicycle, and so on can all be treated as class objects.
Difference between Two Time Periods
In java, Let's look at the many techniques for calculating the difference between two time periods. For the sake of simplicity, let's pretend that the Time Period we've been given is in the format HH:MM:SS.
For example,
Input: 1st Period of time - 18:00:00
2nd period of time - 21:00:00
Output: 3 hours 0 minutes and 0 seconds
Input: 1st Period of time - 17:00:00
2nd Period of time - 23:22:00
Output: 6 hours 22 minutes and 0 seconds
Calculate the Difference between Two Time Periods
public class time {
int sec;
int min;
int hrs;
public time(int hrs, int min, int sec) {
this.hrs = hrs;
this.min = min;
this.sec = sec;
}
public static void main(String[] args) {
// create Time class objects
time start = new time(7, 11, 14);
time stop = new time(11, 33, 54);
time Diff;
// call difference method
Diff = difference(start, stop);
System.out.printf("Time Difference: %d:%d:%d - ", start.hrs, start.min, start.sec);
System.out.printf("%d:%d:%d ", stop.hrs, stop.min, stop.sec);
System.out.printf("= %d:%d:%d\n", Diff.hrs, Diff.min, Diff.sec);
}
public static time difference(time start, time stop)
{
time Diff = new time(0, 0, 0);
// If the start second is larger than the stop seconds, change the minutes of the stop to seconds and finally add seconds to the stop second.
if(start.sec>stop.sec){
--stop.min;
stop.sec += 60;
}
Output
Time Difference: 11:33:54 - 7:11:14 = 4:22:40
We have built a Time class with three-member variables in the above program: hours, minutes, and seconds. They hold hours, minutes, and seconds of a particular time, as their names suggest.
The constructor of the Time class sets hours, minutes, and seconds values.
We have also developed a static method difference, which accepts two Time variables as a parameter, calculates the difference, and returns the difference as a Time class.
Method 1: Using the Date class and the SimpleDateFormat class
In the 7th JDK edition, the SimpleDateFormat class was added to the java.text package. Create a SimpleDateFormat object to parse the Time Period in the HH:MM:SSformat. The Time period is parsed by the SimpleDateFormat object, which returns a Date object, that can be used to calculate the time expired. Below code describe this method:
// Finding the Difference Between Two Time Periods in Java
// The Date Class from the util package is being imported.
importjava.util.*;
// SimpleDateFormat to be imported
// Class from the text package
importjava.text.*;
publicclassJTP {
publicstaticvoidmain(String[] args) throwsException
{
// Dates that must be parsed
String time_1 = "17:00:00";
String time_2 = "5:20:40";
// To parse time in the format, create a SimpleDateFormat object. HH:MM:SS
SimpleDateFormatsimpleDateFormat
= newSimpleDateFormat("HH:mm:ss");
// parsing of the Time Period
Date date_1 = simpleDateFormat.parse(time_1);
Date date_2 = simpleDateFormat.parse(time_2);
// Calculating the millisecond difference
longdifferenceInMilliSeconds
= Math.abs(date_2.getTime() – date_1.getTime());
// Calculating the Hours difference
longdifferenceInHours
= (differenceInMilliSeconds / (60* 60* 1000))
% 24;
// Calculating the Minutes difference
longdifferenceInMinutes
= (differenceInMilliSeconds / (60* 1000)) % 60;
// Calculating the Seconds difference
longdifferenceInSeconds
= (differenceInMilliSeconds / 1000) % 60;
// Print the output
System.out.println(
"The Difference is "+ differenceInHours + " hours "
+ differenceInMinutes + " minutes "
+ differenceInSeconds + " seconds. ");
}
}
Output
The Difference is 11 hours 39 minutes 20 seconds.
Time Complexity:O(1)
Method 2: By using ChronoUnit and LocalTime classes
In the 8th JDK edition, Java has included a slew of new features, including the LocalTime and ChronoUnit classes in java.time package. The date is parsed in the format HH:MM:SS, and the difference in hours, minutes, and seconds is calculated using ChronoUnit. Here is the code for the above method:
// Importing the LocalTime class into a Java program to find the difference between two time periods
importjava.time.*;
// The ChronoUnit class is being imported.
importjava.time.temporal.ChronoUnit;
classJTP{
publicstaticvoidmain(String[] args)
{
// Parsing Time Periods in the HH:MM:SS Format
LocalTime time_1 = LocalTime.of(17, 00, 00);
LocalTime time_2 = LocalTime.of(23, 21, 00);
// Calculating the Hours difference
longhours = ChronoUnit.HOURS.between(time_1, time_2);
// Calculating the Minutes difference
longminutes
= ChronoUnit.MINUTES.between(time_1, time_2) % 60;
// Calculating the Secondsdifference
longseconds
= ChronoUnit.SECONDS.between(time_1, time_2) % 60;
// Print the difference
System.out.println(
"The Difference is "+ hours + " hours "+ minutes
+ " minutes "+ seconds + " seconds.");
}
}
Output:
The Difference is 6 hours 21 minutes 0 seconds.