前言
记一次年底的Bug,是由DateTimeFormatter日期格式化引起的,为避免后续踩坑,特此记录。
切记YYYY和DD谨慎使用
废话不多说,直接上代码。
private static String getDay() {
LocalDate date = LocalDate.of(2020,12,31);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMM");
// 使用YYYYMMDD甚至会报错
// 结果是 202112
return formatter.format(date);
}
欸?明明是2020-12-31为什么格式化之后变成2021-12了?这就是Bug了,若是写在发货日期,那得多等一年才能发货了,这是不能忍的Bug。
我们来看看为什么?
Java’s DateTimeFormatter pattern “YYYY” gives you the week-based-year, (by default, ISO-8601 standard) the year of the Thursday of that week.
YYYY是取的当前周所在的年份,week-based year 是 ISO 8601 规定的。2020-12-31号这一天,根据周算年份属于2021年了,所以格式化之后就变成2021年。
DD也是如此,DD取得是所在年的天数,具体参考点这里
建议使用yyyy和dd
那该如何解了?也很简单,使用yyyy和dd就好了。yyyy是取当前日所在的年份。见代码
private static String getDay() {
LocalDate date = LocalDate.of(2020,12,31);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// 结果是20201231
return formatter.format(date);
}