In this article, we will learn how to calculate the difference between two dates in java in 3 ways with examples.
Java 8 added
ChronoUnit
enum which can be used to calculate difference between two dates in java.It has a
between()
method which accepts two objects and returns the difference between them.
To calculate the difference as days, use DAYS
field of ChronoUnit
as shown below
LocalDate start = LocalDate.of(2023, 9, 1); LocalDate end = LocalDate.of(2023, 12, 1); long days = ChronoUnit.DAYS.between(start, end); System.out.println(days); // 91
between() accepts objects of type Temporal
, which is an interface and LocalDate
implements it.
So, we can pass LocalDate
objects to between()
.
LocalDate class was also added in java 8 and is used to represent a date.
2. until()
LocalDate
has until()
method which accepts another LocalDate
and a unit as arguments and returns the difference between the two dates in that unit. Example,
LocalDate start = LocalDate.of(2023, 9, 1); LocalDate end = LocalDate.of(2023, 12, 1); long diff = start.until(end, ChronoUnit.DAYS); System.out.println(diff); // 91
Unit is supplied as days using ChronoUnit
enum.
Warning
There is an overloaded version of until(), which accepts only 1 argument and returns a Period object.
Period contains time in the form of years, months and days.
To calculate the number of days between two dates, you would be tempted to use Period and its getDays() method.
But, it will lead to incorrect result if the difference is greater than 29.
Suppose there is a difference of 50 days between two dates, then Period will hold it as 0 years, 1 month, 19 days.
So, its getDays()
method will return 19 while you are expected 50.
Calculate the difference between two dates as milliseconds using
java.util.Date
object’s getTime()
method and then convert it to number of days using convert()
method of java.util.concurrent.TimeUnit
class as below
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Date start = sdf.parse("09/01/2023"); Date end = sdf.parse("12/01/2023"); long diff = Math.abs(end.getTime() - start.getTime()); long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); //91
convert()
method accepts a value and the unit of that value and converts it into the unit on which it is called(days in this case).
Hope this was useful.