×

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 Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes 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.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.