×

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

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

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

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.