JDK7及以前的版本,计算两个日期相差的年月日比较麻烦。
JDK8新出的日期类,提供了比较简单的实现方法。
/**
* 计算2个日期之间相差的 相差多少年月日
* 比如:2011-02-02 到 2017-03-02 相差 6年,1个月,0天
* @param fromDate YYYY-MM-DD
* @param toDate YYYY-MM-DD
* @return 年,月,日 例如 1,1,1
*/
public static String dayComparePrecise(String fromDate, String toDate){
Period period = Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));
StringBuffer sb = new StringBuffer();
sb.append(period.getYears()).append(",")
.append(period.getMonths()).append(",")
.append(period.getDays());
return sb.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 {@code LocalDate} from a text string using a specific formatter.
* <p>
* The text is parsed using the formatter, returning a date.
*
* @param text the text to parse, not null
* @param formatter the formatter to use, not null
* @return the parsed local date, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, LocalDate::from);
}
2. 利用Period计算时间差,Period类内置了很多日期计算方法,感兴趣的可以去看源码。Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));主要也是用LocalDate去做计算。Period可以快速取出年月日等数据。
老旧的SimpleDateFormat不是线程安全的,多线程下容易出问题。估计大部分公司都在用JDK8了吧,很多工具类是时候更新换代了,保持与时俱进。
以上。OVER!