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:
- The SimpleDateFormat as well as Date classes are utilized.
- The TimeUnit class is utilized
- 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