×

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included. We frequently have to compute the difference between two dates. There could be several reasons for estimating the date difference.

There are multiple ways to calculate the differences between two dates using Java, among which are the follows:

  1. Using Date and SimpleDateFormat classes
  2. Using TimeUnit class
  3. Using Period class

Now let us examine each of the three methods one by one and explore how these three classes are utilised to determine the date difference in Java.

Using Date and SimpleDateFormat classes

When generating and processing data, the SimpleDateFormat class is utilised. It is employed to transform a date through one format to another. The SimpleDateFormat class is particularly useful when creating a Date object with just a given string date format.

We would utilise either SimpleDateFormat and Date classes to determine the date difference in the following steps.

  1. Construct an SimpleDateFormat class that converts string format into date object.
  2. To generate this date, parse the both start date as well as the end date from such a string that use the simpleDateFormat class parse() method.
  3. With Java, use the getTime() function to determine the time difference between the two dates in milliseconds.
  4. To determine that difference between the two dates, use the date-time mathematical formula. This returns the years, days, hours, minutes, and seconds passed between both the two dates provided.
  5. Print your final result.

The following technique is implemented as follows:

Filename: DifferenceBetweenDates.java

// Java application for the following method
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class DifferenceBetweenDates {
	// Function for printing the differences in
	// time Date1 and Date2
	static void
	findDifference(String Date1, String Date2)
	{
		// SimpleDateFormat modifies the
		// Date object string format
		SimpleDateFormat VAR = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		// Try Block
		try {
			// The parse method is utilized to parse
			// converting text from a string to
			// generate the date
			Date D1 = VAR.parse(Date1);
			Date D2 = VAR.parse(Date2);
			// Determine the time difference
			// in milliseconds
			long TimeDifference= D2.getTime() - D1.getTime();
			// Determine the time difference in
			// seconds, minutes, hours, years,
			// and days
			long SecondsDifference= (TimeDifference/ 1000)% 60;
			long MinutesDifference= (TimeDifference/ (1000 * 60))% 60;
			long HoursDifference= (TimeDifference/ (1000 * 60 * 60))% 24;
			long YearsDifference= (TimeDifference/ (1000l * 60 * 60 * 24 * 365));
			long DaysDifference= (TimeDifference/ (1000 * 60 * 60 * 24))% 365;
			// The date difference should be written in
			// years, in days, in hours, in
			// minutes, and in seconds
			System.out.print("Difference "+ "between the two dates is: ");
			System.out.println(YearsDifference+ " years, "+ DaysDifference+ " days, "+ HoursDifference+ " hours, "+ MinutesDifference+ " minutes, "+ SecondsDifference+ " seconds");
		}
		// Catch the Exception
		catch (ParseException e) {
			e.printStackTrace();
		}
	}
	// Driver Code
	public static void main(String[] args)
	{
		// Given Date1
		String Date1= "23-12-2014 04:15:20";
		// Given Date2
		String Date2= "23-12-2022 11:39:50";
		// Function Call
		findDifference(Date1, Date2);
	}
}

Output:

How to Calculate Time Difference Between Two Dates in Java

Using TimeUnit class

Using TimeUnit class in Java is indeed the easiest approach to discover the date difference. This method for calculating a difference between two dates is exactly the same as when using the SimpleDateFormatClass. The main difference would be that we utilize the built-in TimeUnit class and its methods such as toSeconds(), toMinutes(), toHours(), and toDays() (). Those methods return the days, hours, minutes, and seconds directly.

Now let us examine an example to demonstrate how the TimeUnit class is used to calculate actual date difference.

Filename: DifferenceBetweenDates.java

// Java application to identify
// difference between two dates
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.Date;
class DifferenceBetweenDates {
	// Function for displaying the difference in
	// time Date1 and Date2
	static void findDifference(String Date1, String Date2)
	{
		// SimpleDateFormat transforms the
		// string format to date object
		SimpleDateFormat VAR = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		// Try Class
		try {
			// To parse, use the parse method.
			// converting text from a string to
			// define the date
			Date D1 = VAR.parse(Date1);
			Date D2 = VAR.parse(Date2);
			//Determine the time difference
			// in milliseconds
			long TimeDifference= D2.getTime() - D1.getTime();
			//Determine the time difference in seconds,
			// minutes, hours, years, and days
			long SecondsDifference= TimeUnit.MILLISECONDS.toSeconds(TimeDifference)% 60;
			long MinutesDifference= TimeUnit.MILLISECONDS.toMinutes(TimeDifference)% 60;
			long difference_In_Hours= TimeUnit.MILLISECONDS.toHours(TimeDifference)% 24;
			long DaysDifference= TimeUnit.MILLISECONDS.toDays(TimeDifference)% 365;
			long difference_In_Years= TimeUnit.MILLISECONDS.toDays(TimeDifference)/ 365l;
			// The date difference should be printed in
			// years, in days, in hours, in
			// minutes, and in seconds
			System.out.print("Difference"+ " between the two dates is: ");
			// Print result
			System.out.println(difference_In_Years+ " years, "+ DaysDifference+ " days, "+ difference_In_Hours+ " hours, "+ MinutesDifference+ " minutes, "+ SecondsDifference+ " seconds");
		}
		catch (ParseException e) {
			e.printStackTrace();
		}
	}
	// Driver Code
	public static void main(String[] args)
	{
		// Given Date1
		String Date1= "23-12-2014 04:15:20";
		// Given Date2
		String Date2= "23-12-2022 11:39:50";
		// Function Call
		findDifference(Date1, Date2);
	}
}

Output:

How to Calculate Time Difference Between Two Dates in Java

Using Period class

To determine overall difference between the two days, Java has another significant built-in class. The Period class is used to calculate the difference in terms of days, months, and years. This Period class is identical with the TimeUnit class. The between() method of a period class is now in charge of computing the difference between dates. The Period class has methods such as ofYears(), withMonths(), withYears(), withDays(), toTotalMonths(), ofDays(), ofWeeks(), and ofMonths(), among others.

Now let us examine an example to demonstrate how the period class's between() function may be used to calculate the date difference in days, months, and years.

DifferenceBetweenDates.java

// Java application for the following method
import java.time.*;
import java.util.*;
class DifferenceBetweenDates {
	// Function for printing the difference in
	// time Date1 and Date2
	static void
	findDifference(LocalDate Date1, LocalDate Date2)
	{
		// determine the time difference between
		// the start and end date
		Period diff= Period.between(Date1, Date2);
		// The date difference should be printed.
		// in years, months, and days
		System.out.print("Difference "+ "between the two dates is: ");
		// The result should be printed.
		System.out.printf("%d years, %d months"+ " and %d days ",diff.getYears(),diff.getMonths(),diff.getDays());
	}
	// Driver Code
	public static void main(String[] args)
	{
		// Start date
		LocalDate Date1= LocalDate.of(2011, 10, 07);
		// End date
		LocalDate Date2= LocalDate.of(2022, 10, 07);
		// Function Call
		findDifference(Date1, Date2);
	}
}

Output:

How to Calculate Time Difference Between Two Dates in Java

Related Topics

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

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

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.