java.util.Date计算差异天数 [英] java.util.Date Calculate difference in days

查看:523
本文介绍了java.util.Date计算差异天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算两个日期之间的差异,我注意到一件事。在计算天数时,夏令时间的开始时间将包含在间隔内,所以结果将在1天内缩短。



为了获得准确的结果,



例如:

  SimpleDateFormat format = new SimpleDateFormat(MM-dd-yyyy); 
日期dfrom = format.parse(03-29-2015);
日期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);

输出:

 code> 82800000 
日期:0
营业时间:23

任何人有更好的解决方案?

解决方案

哦,是一个更好的解决方案!



停止使用过时的 java.util.Date 类,并拥抱 java.time API 内置到Java 8和更高版本(教程)。具体来说, DateTimeFormatter LocalDate ChronoUnit 课程。

  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); //打印1


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?

解决方案

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

这篇关于java.util.Date计算差异天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆