怎么查看网站收录,中文域名做的网站有哪些,四川省建设厅安全员报名网站,实体店铺引流推广方法JDK7及以前的版本#xff0c;计算两个日期相差的年月日比较麻烦。JDK8新出的日期类#xff0c;提供了比较简单的实现方法。/*** 计算2个日期之间相差的 相差多少年月日* 比如#xff1a;2011-02-02 到 2017-03-02 相差 6年#xff0c;1个月#xff0c;0天*paramfromDate Y…JDK7及以前的版本计算两个日期相差的年月日比较麻烦。JDK8新出的日期类提供了比较简单的实现方法。/*** 计算2个日期之间相差的 相差多少年月日* 比如2011-02-02 到 2017-03-02 相差 6年1个月0天*paramfromDate YYYY-MM-DD*paramtoDate YYYY-MM-DD*return年,月,日 例如 1,1,1*/public staticString dayComparePrecise(String fromDate, String toDate){Period periodPeriod.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));StringBuffer sb newStringBuffer();sb.append(period.getYears()).append(,).append(period.getMonths()).append(,).append(period.getDays());returnsb.toString();}一个简单的工具方法供参考。简要说2点1. LocalDate.parse(dateString) 这个是将字符串类型的日期转化为LocalDate类型的日期默认是DateTimeFormatter.ISO_LOCAL_DATE即YYYY-MM-DD。LocalDate还有个方法是parse(CharSequence text, DateTimeFormatter formatter)带日期格式参数下面是JDK中的源码比较简单不多说了感兴趣的可以自己去看一下源码/*** Obtains an instance of {codeLocalDate} from a text string using a specific formatter.* * The text is parsed using the formatter, returning a date.**paramtext the text to parse, not null*paramformatter the formatter to use, not null*returnthe parsed local date, not null*throwsDateTimeParseException if the text cannot be parsed*/public staticLocalDate parse(CharSequence text, DateTimeFormatter formatter) {Objects.requireNonNull(formatter,formatter);returnformatter.parse(text, LocalDate::from);}2. 利用Period计算时间差Period类内置了很多日期计算方法感兴趣的可以去看源码。Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));主要也是用LocalDate去做计算。Period可以快速取出年月日等数据。3. 使用旧的Date对象时我们用SimpleDateFormat进行格式化显示。使用新的LocalDateTime或ZonedLocalDateTime时我们要进行格式化显示就要使用DateTimeFormatter。和SimpleDateFormat不同的是DateTimeFormatter不但是不变对象它还是线程安全的。线程的概念我们会在后面涉及到。现在我们只需要记住因为SimpleDateFormat不是线程安全的使用的时候只能在方法内部创建新的局部变量。而DateTimeFormatter可以只创建一个实例到处引用。创建DateTimeFormatter时我们仍然通过传入格式化字符串实现DateTimeFormatter formatter DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm);格式化字符串的使用方式与SimpleDateFormat完全一致。