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

The challenge is to use Java language to determine the difference between two dates.

Given two dates start date as well as the end date with time represented as strings.

Example 1:

Enter the following dates:

start date = 10/01/2018 01:10:20,

end date = 10/06/2020 06:30:50.

Output: 2,152 days, 5,20,30 seconds, or 5,20 hours.

Example 2:

Enter the following dates:

start date and end date: 10-01-2019 and 06-06-2020

Results: 152 days, 5 hours, 0 minutes, and 0 seconds.

Using Java SimpleDateFormat Class

To compare two dates, use the SimpleDateFormat and Date class. the following steps:

  1. Convert a string format to a date object by creating an instance of the SimpleDateFormat class.
  2. To create a date, extract the start date and end date from a string using the simpleDateFormat class's parse() method.
  3. Using the Java method getTime() as d2.getTime() - d1.getTime, determine the time differences between the two dates in milliseconds ().
  4. To determine how two dates differ from one another, use the date-time mathematical formula. The years, days, hours, minutes, and seconds that have passed between the two specified dates are returned.
  5. Print the finished product.

The aforesaid strategy is put into practice as follows:

File name: TimeDiff1.java

Output:

The difference between the two dates is: -2 years, -152 days, -5 hours, -20 minutes, -30 seconds

Using Java TimeUnit Class

By using the Java built-in class TimeUnit, we may more accurately determine the difference among the two dates. The aforesaid method is put into practice as follows:

File name: TimeDiff2.java

Output:

The difference between the two dates is: 2 years, 151 days, 4 hours, 20 minutes, 30 seconds

Using Java Period Class

Java's Period class can be used to calculate the distinction between two days. The difference in months, days, and years between two dates can be determined using the Period.between() method. The aforesaid strategy is put into practice as follows:

File name: TimeDiff3.java

Output:

The difference between the two dates is: 3 years, 5 months, and 0 days