×

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

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 Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

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.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

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

4 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

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.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

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

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.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.