踩坑:java时间格式化yyyy与YYYY的区别

查询数据时发现一个bug,前端传了2021-12-28这个日期,转成String类型居然变成了2022-12-28.

经过各种排查,锁定问题可能出现在一个时间转换代码上
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

经过百度发现YYYY代表的含义,和yyyy是不一样的

简单来说,一年有52周,超过52周的,年份+1,2021年有52个周,28号属于第53周,所以会出现年份+1

Java's DateTimeFormatter pattern "YYYY" gives you the week-based-year, (by default, ISO-8601 standard) the year of the Thursday of that week.

The unit that represents week-based-years for the purpose of addition and subtraction.
This allows a number of week-based-years to be added to, or subtracted from, a date. The unit is equal to either 52 or 53 weeks. The estimated duration of a week-based-year is the same as that of a standard ISO year at . 365.2425 Days

The rules for addition add the number of week-based-years to the existing value for the week-based-year field. If the resulting week-based-year only has 52 weeks, then the date will be in week 1 of the following week-based-year.

原文地址:https://www.cnblogs.com/inkyi/p/15740946.html