Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Date Calculate difference in days

I tried to calculate the difference between two dates and I noticed one thing. When calculating only the days, the start of daylight saving time is included in the interval, so the result will be shorter with 1 day.

To obtain accurate results, the value of hours also must be considered.

For example:

SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
Date dfrom = format.parse("03-29-2015");
Date dto = format.parse("03-30-2015");
long diff = dto.getTime() - dfrom.getTime();
System.out.println(diff);
System.out.println("Days: "+diff / (24 * 60 * 60 * 1000));
System.out.println("Hours: "+diff / (60 * 60 * 1000) % 24);

Output:

82800000
Days: 0
Hours: 23

Does anybody have a better solution?

like image 461
tib Avatar asked Oct 02 '15 10:10

tib


People also ask

How do I subtract days from a date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31.

How do I compare two Java Util dates?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How do I calculate the number of days between two dates in Java 8?

In Java 8, we can use ChronoUnit. DAYS. between(from, to) to calculate days between two dates.


1 Answers

Oh yes a better solution there is!

Stop using the outmoded java.util.Date class and embrace the power of the java.time API built into Java 8 and later (tutorial). Specifically, the DateTimeFormatter, LocalDate, and ChronoUnit classes.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate date1 = LocalDate.parse("03-29-2015", formatter);
LocalDate date2 = LocalDate.parse("03-30-2015", formatter);
long days = ChronoUnit.DAYS.between(date1, date2);
System.out.println(days); // prints 1
like image 199
Tunaki Avatar answered Sep 20 '22 20:09

Tunaki