Java has many ways to get the time difference between two dates, from simple methods like using the Date class to advanced methods. The Java standard library and third-party libraries provide classes and methods to calculate the months between two dates.
In this blog, we will learn in detail about the different methods that can be used to calculate the difference between any two dates.
Table of contents:
What are Java Date Instances?
In Java, Date instances are objects that are used to represent particular points in time or calendar dates. Java classes are utilized to create Date instances for handling and working with date and time data. Java, over time, progressed from older Date and Calendar classes to more robust and contemporary java.time API available in Java 8.
Common Instance Classes of Java Date.
Here are several common classes to create and work with date instances:
1. java.util.Date
- Represents an instant in time, to millisecond accuracy.
- Now deprecated and superseded by the java.time classes.
- Example: Date date = new Date();
2. java.util.Calendar
- An alternative, more flexible option to Date, which can have each date field manipulated.
- Still relatively flawed and wordy.
3. java.time.LocalDate (Java 8+)
- Represents an empty date (year, month, day).
- Perfect for birthdays or special anniversaries.
- Example: LocalDate date = LocalDate.of(2025, 5, 9);
4. java.time.LocalTime
- Represents time without date (hours, minutes, seconds).
- Useful where time-of-day is only relevant.
5. java.time.LocalDateTime
- Represents date and time without any time-zone.
- Typically utilized for local application time stamps.
6. java.time.ZonedDateTime
- Date, time, and time-zone are combined.
- Ideal for worldwide use with several time zones.
7. java.time.Instant
- Represents an Instant, or an instant in time on the UTC time-line.
- Suitable for accurate time tracking and calculations.
Methods of Calculating the Difference between Two Java Date Instances
In Java, there are several ways to calculate the difference between two Dates or times. Some of them are:
This method parses the date string into a Date object using SimpleDateFormat and then simply calculates the difference between the getTime() values of the two Date instances.
SimpleDateFormat is used to define the date format and parse the date strings into Date objects.
Steps of using SimpleDateFormat and Date Class:
1. Parsing Date Strings: By using the SimpleDateFormat you can parse the date string(yyyy-MM-dd HH:mm:ss) into the Date objects.
2. Subtracting Dates: Once you have the Date objects, you can get the time in milliseconds using the getTime() method.
3. Calculating the Difference: Subtract the above two time values and then convert them into days, hours, minutes, or seconds.
Example:
Output:
Explanation: The above program finds the difference between the two dates in days, hours, minutes, and seconds. It parses the date strings into Date objects, gets the time difference in milliseconds, and then converts it into various time units.
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
Method 2: Using TimeUnit Class in Java
The TimeUnit class in Java is used to convert the time differences between many units like milliseconds, seconds, minutes, hours, etc., without doing the manual calculations. It is part of the java.util. package and is used to do the changes like milliseconds to seconds, minutes, hours, or days.
Example:
Output:
Explanation: The above program takes two times before and after a 20-second, then calculates the time difference in milliseconds, and converts it into hours, minutes, and seconds using the TimeUnit method. This method is good because it makes all the changes of the units by itself and makes the code clean and easy to maintain.
Method 3: Using LocalDate and ChronoUnit Class in Java
In Java 8 and later, the java.time package gives better usage of the dates and times with classes like LocalDate for the date without time and LocalDateTime with date and time. The ChronoUnit class calculates the difference between the two LocalDate or LocalDateTime easily.
Steps of Using LocalDate and ChronoUnit Class in Java:
1. Use LocalDate or LocalDateTime: The LocalDate class defines a date without a time, and LocalDateTime includes both the date and time.
2. Calculate the Difference: Use the ChronoUnit.DAYS.between() method to calculate the difference in the various units.
Example:
Output:
Explanation: The above Java program uses LocalDate and ChronoUnit.DAYS to find the day difference between two dates. It does not do changes in the units and hence makes the code readable and accurate.
Method 4: Using Period Class (For Date Difference in Years, Months, and Days) in Java
The Period class in Java is used for calculating the difference between two LocalDate objects of years, months, and days. This is helpful when you are using dates that use years and months. To use the Period.between() method, two LocalDate objects are needed, i.e., the Start Date and the End Date. It calculates the difference between the two dates and then breaks it into three i.e., in years, months, and days.
Note: You should be careful when you are using the dates. If the start date comes after the end date, the result will be negative for years, months, and days. Negative values are used for overdue checks or validating the date inputs.
Steps of Using Period Class:
1. Using LocalDate: Create two LocalDate objects, date1 and date2
2. Calculating the Period: Use the Period.between() method to get the difference in years, months, and days.
Example:
Output:
Explanation: The above Java program uses the LocalDate and Period to calculate the difference between two dates in years, months, and days. Two LocalDate instances are created, and then the difference with the help of Period.between() method is calculated.
Unlock Your Future in Java
Start Your Java Journey for Free Today
Method 5: Using the Duration.between() in Java
The Duration.between() method is a part of the java.time package, which is a modern API for using the date and time. This method finds the difference between the two Temporal objects like LocalDateTime, Instant, or ZonedDateTime and gives the result as a Duration object, which shows a time difference in seconds and nanoseconds.
But like Period.between(), which is used to calculate differences in terms of years, months, and days, the Duration.between() method is used for calculating the difference in terms of time units such as seconds, minutes, hours, and milliseconds.
Syntax:
Duration duration = Duration.between(startDateTime, endDateTime);
Example:
Output:
Explanation: The above code finds the time difference between two LocalDateTime values, i.e. start and end. Then it uses Duration.between() to calculate the difference and then gives the result in hours, minutes, and seconds.
Method 6: Using the JodaTime Library in Java
Joda-Time is a library that is used for date and time operations in Java. It was earlier used in older Java projects because it was simple and easy to use. You can use Joda-Time to calculate the difference between two dates or times in a flexible manner than the old Date class as it handles the time zones and formatting in an efficient manner.
Steps to Use Joda-Time for Date Difference:
1. Adding Joda-Time to the Project: First, include the Joda-Time library in your project. If you are using Maven, add the following dependency to your pom.xml:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.10</version> <!--use the latest version -->
</dependency>
2. Creating DateTime Objects: Use the DateTime class from Joda-Time to create your dates and times.
3. Calculating the Difference: Use the Days, Hours, Minutes, or Seconds class to get the difference in the required unit.
Example:
Output:
Explanation: The above code uses the Joda-Time library for calculating the difference in days between the two dates. It creates two DateTime objects for the start and the end dates. Then the Days.daysBetween(start, end) method finds the number of days between the dates.
Method 7: Using the Temporal#until() in Java
The Temporal#until() method in Java is used with Temporal objects like LocalDate, LocalDateTime, or ZonedDateTime. It calculates the amount of time between the two Temporal objects in a unit such as days, hours, months, etc.
This method is a part of the Temporal interface in Java which allows you to find the difference between the two Temporal objects like ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MONTHS, and more.
Syntax:
long until(Temporal endExclusive, TemporalUnit unit);
where:
endExclusive is The Temporal object representing the end point,
Unit is the unit of time
Example:
Output:
Explanation: The above code shows the until() method is calculating the difference between the two dates or times. It calculates the days between two LocalDate objects, the hours between LocalDateTime objects, and the minutes between ZonedDateTime objects. It also calculates seconds and hours with time zones and months between the LocalDate objects.
Pros and Cons of Various Java Date Difference Calculation Methods
Methods |
Advantages |
Disadvantages |
SimpleDateFormat and Date Class |
Simple to understand and implement.Works in older Java versions. |
Requires manual conversion for time units.Doesn't handle time zones efficiently. |
Using TimeUnit Class |
More readable.Prevents rounding errors.Converts milliseconds easily to days, hours, minutes, and seconds. |
Cannot calculate differences in months or years. |
Using LocalDate and ChronoUnit Class |
Cleaner and more readable syntax.Handles differences in days, months, and years easily. |
Only works with LocalDate, not LocalDateTime. |
Using Period Class |
Ideal for calculating differences in years, months, and days.More human-readable results. |
Cannot calculate differences in hours, minutes, or seconds.Works only with LocalDate. |
Using Duration.between() |
Best for calculating differences in hours, minutes, seconds, and nanoseconds.Works well with LocalDateTime, Instant, and ZonedDateTime. |
Cannot calculate differences in days, months, or years directly.Works with Temporal objects, so conversion may be needed for LocalDate. |
Using Joda-Time Library |
More flexible than Date and Calendar.Provides better time zone handling.Supports both date and time difference calculations. |
Adds an extra dependency to the project. |
Using Temporal#until() |
Works with LocalDate, LocalDateTime, and ZonedDateTime.Modern and efficient. |
More complex syntax Less commonly used |
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
There are many ways to calculate the difference between two dates in Java. Simple methods like SimpleDateFormat and Date class have simple calculations, and TimeUnit offers conversions. Recent Java methods like LocalDate, ChronoUnit, and Period have simple calculations for dates. Duration.between() method is used to calculate time differences, and the Temporal#until() method is used to calculate differences in any unit other than time. The data is handled in an easy manner using Joda-Time libraries.
If you want to learn more about Java, you can refer to our Java Course.
Difference between Two Java Date Instances - FAQs
Q1. How can the difference between two datetime instances be calculated?
To get the difference between two dates, subtract date2 from date1.
Q2. How to get the number of days difference between two dates in Java?
If we want to calculate the difference in days, the ChronoUnit. DAYS. between() method is the best way
Q3. What is greater than date comparison?
“Greater than” and “Less than” operators compare the chronological order of the two datesx
Q4. How to check if dates overlap in Java?
The overlaps() method takes two Interval objects as parameters and returns true if there is any intersection between the two intervals.
Q5. How to check if two dates are equal in Java?
The .equals() method of the Date class compares the current Date object to the specified object.