java.util.Date计算差异天数 [英] java.util.Date Calculate difference in days
问题描述
为了获得准确的结果,
例如:
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屋!