Introduction
More often than not we find ourselves counting the number of days from or to a particular date. Luckily, doing just that in Java is not very hard, and there are also quite a few ways to do it.
So, in this article, we'll be taking a look at how to get the number of days between two dates in Java.
Finding the Difference Between Two Dates Prior to Java 8
This is one of the easiest and most straightforward ways to calculate the difference in days between two dates. In order to do it, we need to have two Date
objects. Using the getTime()
from java.util.Date
class, we'll be getting the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by a specific Date
object.
Note: This specific time is no coincidence either, as it's often referred to as the beginning of the UNIX Epoch or UNIX Time.
After getting the time in milliseconds, we'll get the difference between two values by subtracting them and converting the new value to days - either manually (by doing a simple calculation) or by using TimeUnit.DAYS.convert
method from java.util.concurrent.TimeUnit
.
We can get dates either as a Date
or a String
object. In the second case, we need to convert a String
to a Date
using the parse
method from the SimpleDateFormat
class.
Let's calculate the number of days of two example dates:
Date dateBefore = new Date(2022, Calendar.APRIL, 21);
Date dateAfter = new Date(2022, Calendar.APRIL, 25);
long dateBeforeInMs = dateBefore.getTime();
long dateAfterInMs = dateAfter.getTime();
long timeDiff = Math.abs(dateAfterInMs - dateBeforeInMs);
long daysDiff = TimeUnit.DAYS.convert(timeDiff, TimeUnit.MILLISECONDS);
// Alternatevly:
// int daysDiff = (int) (timeDiff / (1000 * 60 * 60 * 24));
System.out.println(" The number of days between dates: " + daysDiff);
Since there are four days between our example dates, the previous code will produce the following output:
The number of days between dates: 4
As mentioned earlier, if we've used a String
instead of a Date
object, we'd first need to convert it for it to be usable. In order to convert a String
to a Date
, we need to first define which date format we'll be using in order to parse the values correctly. In our example, we'll be using the MM/dd/yyyy
format. After that, we parse the String
to a Date
, and do the same as we did in the previous example:
try {
// Convert `String` to `Date`
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date dateBefore = sdf.parse("04/21/2022");
Date dateAfter = sdf.parse("04/25/2022");
// Calculate the number of days between dates
long timeDiff = Math.abs(dateAfter.getTime() - dateBefore.getTime());
long daysDiff = TimeUnit.DAYS.convert(timeDiff, TimeUnit.MILLISECONDS);
System.out.println("The number of days between dates: " + daysDiff);
}catch(Exception e){
e.printStackTrace();
}
We first defined a new SimpleDateFormat
so that we know how to parse out the dates given through the String
, after which we use the method parse
to do just that. The only thing we need to pay attention to here is that we need to surround this portion of the code with a try-catch
block, since the parse
method can cause an error breaking our program. Finally, after we've calculated the time difference, we again apply the TimeUnit.DAYS.convert
method to convert it to days and produce the following output:
The number of days between dates: 4
Finding the Difference Between Two Dates Using java.time.temporal.ChronoUnit
ChronoUnit
is an enum
that implements the TemporalUnit
interface, which provides the standard units used in the Java Date Time API (essentially, a standard set of date periods units). This set of units provides unit-based access to manipulate a date, time, or date-time.
ChronoUnit
has only a few methods, and the one that interests us the most is the between()
method. This method takes in two Temporal
objects and calculates the amount of time between them. The start and end points must be of compatible types. The implementation will convert the second type to be an instance of the first type before calculating the amount. The calculation returns a whole number, representing the number of complete units between the two temporals.
Note: The result will be negative if the end date is before the start date.
There are two different ways of using the between()
method. The first is to invoke this method directly. The second is to use Temporal.until(Temporal, TemporalUnit)
which invokes it implicitly:
try {
LocalDate dateBefore = LocalDate.parse("2022-04-21");
LocalDate dateAfter = LocalDate.parse("2022-04-25");
// Approach 1
long daysDiff = ChronoUnit.DAYS.between(dateBefore, dateAfter);
System.out.println("The number of days between dates: " + daysDiff);
// Approach 2
long daysDiff = dateBefore.until(dateAfter, ChronoUnit.DAYS);
System.out.println("The number of days between dates: " + daysDiff);
}catch(Exception e){
e.printStackTrace();
}
Both of these produce the same result:
The number of days between dates: 4
Finding the Difference Between Two Dates Using java.Time.Period
The Period
class is a date-based class, meaning that it models a quantity (amount) of time in terms of years, months, and days - for example '3 years, 5 months, and 7 days'. It has a time-based equivalent, the Duration
class, that models the amount of time in terms of seconds and nanoseconds.
Durations and periods differ in their treatment of daylight savings time when added to ZonedDateTime
. A Duration
will add an exact number of seconds, thus the duration of one day is always exactly 24 hours. By contrast, a Period
will add a conceptual day, trying to maintain the local time.
The Period
class has a between()
method - just as the previously discussed ChronoUnit
. This method takes in two LocalDate
objects, one representing the starting date, and the second being the end date. It returns a Period
consisting of the number of years, months, and days between two dates. It's important to note that the start date is included, while the end date is not.
Let's see an example of how we can use this method:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
LocalDate dateBefore = LocalDate.of(2022, 4, 21);
LocalDate dateAfter = LocalDate.of(2022, 4, 25);
Period period = Period.between(dateBefore, dateAfter);
long daysDiff = Math.abs(period.getDays());
System.out.println(" The number of days between dates: " + daysDiff);
This works fine and will produce the same result as all the previous examples we had. However, there's a big problem with this approach if you want to calculate the time of days between months:
LocalDate dateBefore = LocalDate.of(2022, 2, 21);
LocalDate dateAfter = LocalDate.of(2022, 4, 25);
If we calculated the difference between these two dates, the expected answer should be 63 days. However, the output we get again is 4 days. The reasoning behind this is that again - Periods include the number of years, months and days as separate entities. We can't "sum up" the months and years into days natively, so you'd have to create an extra method for that:
static long getDayDiff(Period period) {
long years = period.getYears();
long months = period.getMonths();
long days = period.getDays();
return (years*365)+(months*30)+days;
}
Though, this is still only an approximation that doesn't take leap years into account, nor whether a month has 30 or 31 days. All of the if-clauses and checks could get pretty verbose quickly, so it's highly advised to stick to the between()
method for getting the number of days between dates.
Finding the Difference Between Two Dates Using Joda-Time
The standard date and time classes before Java 8 were known to be poor, and so Joda-Time
became the standard date and time library that was most widely used at the time. The design allows for multiple calendar systems, while still providing a simple API. Most of the calendar systems were included, as well as supporting classes for time zones, duration, format, and parsing.
Note: This section was added for legacy systems that still use Joda-Time, instead of the new Date/Time API. If you're using a newer version of Java, it's preferable, easier and more performant to not include new dependencies.
Adding Joda-Time
to our project requires adding the following dependency from Maven Central:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.14</version>
</dependency>
We won't be diving deeper into everything that the Joda-Time
library offers, and if you're interested further you can check the official Joda-Time website.
Now that we've added the library to our project, getting the difference between dates is very simple, and not at all different to the approaches prior:
org.joda.time.LocalDate dateBefore = org.joda.time.LocalDate.parse("2022-04-21");
org.joda.time.LocalDate dateAfter = org.joda.time.LocalDate.parse("2022-04-25");
long daysDiff = Math.abs(Days.daysBetween(dateBefore, dateAfter).getDays());
System.out.println(" The number of days between dates: " + daysDiff);
Although useful, this library is practically "overrun" by the overhaul of how time and dates are formatted in Java 8, and offers practically no benefits compared to the previous approaches discussed. However, if you're for whatever reason using a version older than Java 8, this is the best way to do it.
Conclusion
In this article we've taken a look at how to do one of the most basic tasks in programming - find the number of days between two dates. Firstly, we did this in the simplest way possible, and then examined several alternative approaches - the ChronoUnit
enum, the Duration
and the Period
classes from java.time
. Finally, we've taken a look at how to calculate the number of days between two dates it using a widely popular external library like Joda-Time
, for a much more elegant approach to solving this problem.