Calculate difference between two dates in Java
This post will discuss how to calculate the difference between two dates in Java.
1. Using TimeUnit.convert() method
The idea is first to get the difference between two dates in milliseconds using the Date.getTime() method. Then we can use the convert() method from java.util.concurrent.TimeUnit enum to convert the given time duration in the given unit to the unit of the argument.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; class Main { public static void main(String[] args) { String d1 = "10-20-2016"; String d2 = "10-19-2016"; String pattern = "MM-dd-yyyy"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { Date date1 = sdf.parse(d1); Date date2 = sdf.parse(d2); // get the difference between two dates in minutes long elapsedms = date1.getTime() - date2.getTime(); long diff = TimeUnit.MINUTES.convert(elapsedms, TimeUnit.MILLISECONDS); System.out.println(diff); } catch (ParseException e) { e.printStackTrace(); } } } |
Output:
1440
Please note that the above code snippet doesn’t consider time zones as java.util.Date is always in UTC. Also, this won’t consider daylight savings.
2. Using java.time package
From Java 8 onward, we should use the java.time package that offers a lot of improvement over the existing Java date-time API. Here’s how we can calculate the difference between two dates as a Duration in Java 8 and above.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.time.Duration; import java.time.ZonedDateTime; class Main { public static void main(String[] args) { ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime then = now.minusMonths(2).minusDays(10) .minusMinutes(5).minusSeconds(40); Duration duration = Duration.between(then, now); System.out.println(duration); // System.out.println(duration.getSeconds()); // System.out.println(duration.toMinutes()); // System.out.println(duration.toHours()); // System.out.println(duration.toDays()); } } |
Output:
PT1704H5M40S
If you have a java.util.Date object, you should convert it into java.time.Instant and then calculate the elapsed time as a Duration.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.util.Date; class Main { public static void main(String[] args) { String d = "12/25/2018"; SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); try { Date date = sdf.parse(d); Duration duration = Duration.between(date.toInstant(), Instant.now()); System.out.println(duration); } catch (ParseException e) { e.printStackTrace(); } } } |
Output:
PT3880H26M38.942S
3. Using Joda Time
Before Java 8, many Java projects have used the Joda-Time library for Date and Time classes. This is because the standard date and time classes before Java 8 are poor. But with the introduction of the java.time package in Java SE 8, the Joda-Time team have asked their users to migrate to java.time (JSR-310).
If you are using the Joda-Time library in your project and just want the total number of whole days between two dates, you can use the new Days class in version 1.4 of Joda-Time.
|
1 2 |
Days d = Days.daysBetween(startDate, endDate); int days = d.getDays(); |
If you want to calculate the total number of days, weeks, months, and years between the two dates, you need a Period. By default, this will split the difference between the two date-times into parts, such as “1 month, 2 weeks, 4 days and 7 hours”.
|
1 |
Period p = new Period(startDate, endDate); |
You can control which fields get extracted using a PeriodType.
|
1 |
Period p = new Period(startDate, endDate, PeriodType.yearMonthDay()); |
This example will return no weeks or time fields; thus, the previous example becomes “1 month and 18 days”.
That’s all about calculating the difference between two dates in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)