java. util. Date calculation days difference

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

To obtain accurate results, the hourly value must also 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 anyone have a better solution?

Solution

Oh, yes, there is a better solution!

Stop using outdated Java util. Date class and embrace the Java. Date class built in Java 8 and later (Tutorial) Powerful functions of time API Specifically, they are datetimeformatter, localdate and chrononunit 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>