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 period=Period.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完全一致。