×

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between the two dates must frequently be calculated. There are various methods for determining the date difference.

Methods

There are several methods in Java for finding the distinction between different dates, including the ones listed below:

  1. The SimpleDateFormat as well as Date classes are utilized.
  2. The TimeUnit class is utilized
  3. Throughout the Period class

The SimpleDateFormat as well as Date classes are utilized

The data is formatted and parsed using the SimpleDateFormat class. It is utilized to change a date's format from one to another. The SimpleDateFormat class comes in handy when creating Date objects with a certain string date format.

We will utilize the SimpleDateFormat as well as Date classes in combination to perform the following procedures to determine the date difference.

  • Construct an object
    The string date format will be transformed into a date object in the first step by creating an application of the SimpleDatFormat class.
  • Parse the date
    For parsing the string date-to-date object format, we will use the class's parse() method.
  • Use the getTime() function
    The getTime() method will be used in the following step to determine the difference between the two dates. The difference will be measured in milliseconds.
  • Utilize a mathematical formula
    The mathematical formula can also be used to calculate the difference in years, days, hours, minutes, and seconds.

Print the outcome

The difference between the two dates will be printed last.

To see how we can put the preceding stages into practice, let's look at an example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


class Demo {
	static void
	findDifference(String start_date,
				String end_date)
	{
		SimpleDateFormatsdf
			= new SimpleDateFormat(
				"dd-MM-yyyyHH:mm:ss");
		try {
			Date d1 = sdf.parse(start_date);
			Date d2 = sdf.parse(end_date);
			long difference_In_Time
				= d2.getTime() - d1.getTime();
			long difference_In_Seconds
				= (difference_In_Time
				/ 2000)
				% 60;


			long difference_In_Minutes
				= (difference_In_Time
				/ (2000 * 60))
				% 60;


			long difference_In_Hours
				= (difference_In_Time
				/ (2000 * 60 * 60))
				% 24;


			long difference_In_Years
				= (difference_In_Time
				/ (2000l * 60 * 60 * 24 * 365));


			long difference_In_Days
				= (difference_In_Time
				/ (2000 * 60 * 60 * 24))
				% 365;


			System.out.print(
				"The Difference "
				+ "betweenthe  two dates is: ");


			System.out.println(
				difference_In_Years
				+ " years, "
				+ difference_In_Days
				+ " days, "
				+ difference_In_Hours
				+ " hours, "
				+ difference_In_Minutes
				+ " minutes, "
				+ difference_In_Seconds
				+ " seconds");
		}


		// Catch the Exception
		catch (ParseException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args)
	{
		String start_date
			= "11-02-2019 02:20:30";
		String end_date
			= "11-07-2021 07:40:30";
		findDifference(start_date, end_date);
	}

Output

The difference between the two dates is: 1 years, 75 days, 14 hours, 40 minutes, 0 seconds

The TimeUnit class is utilized

Java's TimeUnit class, which is the best method for determining the date difference, is available. Finding that distinction between the two dates is accomplished using the same method as when using the SimpleDateFormatClass.

The main distinction is that we utilise the built-in TimeUnit class and its toSeconds(), toMinutes(), toHours(), and toDays() methods (). The days, hours, minutes, and seconds are directly returned by these functions.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.Date;
class Demo {
	static void findDifference(String start_date,
							String end_date)
	{
		SimpleDateFormatsdf
			= new SimpleDateFormat(
				"dd-MM-yyyyHH:mm:ss");
		try {
			Date d1 = sdf.parse(start_date);
			Date d2 = sdf.parse(end_date);
			long difference_In_Time
				= d2.getTime() - d1.getTime();
			long difference_In_Seconds
				= TimeUnit.MILLISECONDS
					.toSeconds(difference_In_Time)
				% 60;
			long difference_In_Minutes
				= TimeUnit
					.MILLISECONDS
					.toMinutes(difference_In_Time)
				% 60;
			long difference_In_Hours
				= TimeUnit
					.MILLISECONDS
					.toHours(difference_In_Time)
				% 24;
			long difference_In_Days
				= TimeUnit
					.MILLISECONDS
					.toDays(difference_In_Time)
				% 365;
			long difference_In_Years
				= TimeUnit
					.MILLISECONDS
					.toDays(difference_In_Time)
				/ 365l;
			System.out.print(
				"The Difference"
				+ " betweenthe  two dates is: ");
			System.out.println(
				difference_In_Years
				+ " years, "
				+ difference_In_Days
				+ " days, "
				+ difference_In_Hours
				+ " hours, "
				+ difference_In_Minutes
				+ " minutes, "
				+ difference_In_Seconds
				+ " seconds");
		}
		catch (ParseException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args)
	{
		String start_date
			= "11-02-20189 02:20:10";
		String end_date
			= "12-07-2021 07:40:30";
		findDifference(start_date,
					end_date);
	}
}

Output

The difference between the two dates is: -18179 years, -239 days, -18 hours, -39 minutes, -40 seconds

Throughout the Period class

Another significant built-in class in Java is available and is highly beneficial for determining the contrast between the different days. To calculate the difference in days, months, and years, we are using the Period class. The TimeUnit class and the Period class are related. Calculating the gap between dates is done via the between the () function of the period class. Numerous methods, including ofYears(), withMonths(), withYears(), withDays(), toTotalMonths(), ofDays(), ofWeeks(), as well as ofMonths(), are available in the Period class.

To further understand how to obtain the date differential in days, months, as well as years using the time class between() method, let's look at an example.

import java.time.*;
import java.util.*;
class Demo {
	static void
	findDifference(LocalDatestart_date,
				LocalDateend_date)
	{
		Period diff
			= Period
				.between(start_date,
						end_date);
		System.out.print(
			" The Difference "
			+ "between the two dates is: ");
		System.out.printf(
			"%d years, %d months"
				+ " and %d days ",
			diff.getYears(),
			diff.getMonths(),
			diff.getDays());
	}
	public static void main(String[] args)
	{
		LocalDatestart_date
			= LocalDate.of(2019, 02, 11);
		LocalDateend_date
			= LocalDate.of(2021, 07, 8);
		findDifference(start_date,
					end_date);
	}
}

Output

The Difference between the two dates is: 2 years, 4 months and 27 days

Related Topics

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

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.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

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

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.