Difference Between Two Dates in Java

There are multiple approaches available to determine the disparity between dates. Among them, one of the simplest methods involves calculating the difference between two Date objects by measuring the number of milliseconds between them and subsequently dividing that value by the number of milliseconds in a 24-hour duration. To ensure accuracy and adherence to standard practices, the following guidelines should be followed:

1000 milliseconds = 1 second 60 seconds = 1 minute 60 minutes = 1 hour 24 hours = 1 day

That is, dateDifference in milliseconds/(1000 * 60 * 60 * 24) )

  1. This won't take time zones into consideration - Date is always in UTC
  2. This won't take daylight saving time into consideration (where there can be days which are only 23 hours long, for example)

The following Java program calculate the difference between two dates:

import java.text.SimpleDateFormat; import java.util.Date; public class TestClass { public static void main(String[] args) { SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy"); String inputString1 = "10 03 1995"; String inputString2 = "14 03 1995"; try{ Date oldDate = myFormat.parse(inputString1); Date newDate = myFormat.parse(inputString2); int diffInDays = (int)( (newDate.getTime() - oldDate.getTime()) / (1000 * 60 * 60 * 24) ); System.out.println(diffInDays); }catch(Exception ex){ System.out.println(ex); } } }

Date difference in java 8

Accurately calculating the difference between two dates in Java can prove to be quite challenging, especially without utilizing a third-party library. Unless you possess the time and resources to develop your own Java library, such as Joda, which specifically addresses the complexities associated with date and time calculations, achieving precise results can be a daunting task. However, there is good news to alleviate these concerns. With the introduction of Java 8, the third time seems to be the charm.

Java 8 made its initial foray into improving the existing date/time API, aiming to provide enhanced capabilities and more convenient operations for handling dates and times in Java applications. This update offers a glimmer of hope for developers by introducing features and functionalities that simplify date/time calculations and improve the overall usability of the API.

Example
import java.time.LocalDate; import java.time.Period; public class TestClass { public static void main(String[] args) { LocalDate oldDate = LocalDate.of(1995, 05, 01); LocalDate now = LocalDate.now(); Period diff = Period.between(oldDate, now); System.out.printf("Date Difference is %d years, %d months and %d days old", diff.getYears(), diff.getMonths(), diff.getDays()); } }

Daylight Saving Time solution

Daylight Saving Time (DST) is a widely practiced method of adjusting clocks by advancing them one hour ahead of standard time during the summer months. This practice aims to maximize the utilization of natural daylight. However, the aforementioned approach presented challenges for us when daylight saving time transitions occurred. To address this, we have devised an alternative solution that effectively handles all dates without relying on external libraries like JodaTime.

Following solution uses calendar objects to navigate the intricacies of DST and accurately calculate date and time differences. By utilizing the inherent functionalities of Java's built-in calendar system, we can ensure reliable and consistent results when dealing with various time zones and daylight saving time transitions. This solution provides a robust and self-contained approach that eliminates the need for additional dependencies, offering a more streamlined and efficient implementation for handling date and time calculations in Java applications.

import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class TestClass { public static void main(String[] args) { Calendar calendar1 = Calendar.getInstance(); Calendar calendar2 = Calendar.getInstance(); calendar1.set(1995, 03, 02); calendar2.set(1995, 03, 06); int diff = dateFiff(calendar1,calendar2); System.out.println(diff); } public static int dateFiff(Calendar date1, Calendar date2){ if (date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR)) { return Math.abs(date1.get(Calendar.DAY_OF_YEAR) - date2.get(Calendar.DAY_OF_YEAR)); } else { if (date2.get(Calendar.YEAR) > date1.get(Calendar.YEAR)) { Calendar temp = date1; date1 = date2; date2 = temp; } int resultDays = 0; int dayOneOriginalYearDays = date1.get(Calendar.DAY_OF_YEAR); while (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) { date1.add(Calendar.YEAR, -1); resultDays += date1.getActualMaximum(Calendar.DAY_OF_YEAR); } return resultDays - date2.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ; } } }