×

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:

  1. 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.
  2. 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.

Related Topics

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.