DateTimeFormatter giving wrong format for edge cases [duplicate]

只愿长相守 提交于 2021-02-19 01:11:50

问题


DateTimeFormatter is not giving correct format for Dec 30 and 31 2018 as per following snippet.

final String DATE_FORMAT = "YYYYMM";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(DATE_FORMAT);
LocalDateTime startDate = LocalDateTime.of(2018,12,29,5,0,0);
System.out.println(startDate.format(dateFormat));
//prints 201812
LocalDateTime startDate = LocalDateTime.of(2018,12,30,5,0,0);
System.out.println(startDate.format(dateFormat));
//prints 201912 <------ should be 201812
LocalDateTime startDate = LocalDateTime.of(2018,12,31,5,0,0);
System.out.println(startDate.format(dateFormat));
//prints 201912 <------ should be 201812

Is this the expected behavior or is there a bug with DateTimeFormatter?


回答1:


YYYY is week year, yyyy is year

So Change final String DATE_FORMAT = "YYYYMM"; ro final String DATE_FORMAT = "yyyyMM"; should give you the correct result. For more informations about the patterns see the javadoc of DateTimeFormatter.

The first week of 2019 starts at Dec 30 of 2018. See this link for more informations about the wee years




回答2:


This is expected behaviour. YYYY stands for "week-based-year", which is not the same as calendar year (see JavaDoc)

You most probably want to use yyyy, which means "year-of-era"




回答3:


y is for "year-of-era" while Y is for week-based-year

Replace:

final String DATE_FORMAT = "YYYYMM";

to:

final String DATE_FORMAT = "yyyyMM";


来源:https://stackoverflow.com/questions/54070493/datetimeformatter-giving-wrong-format-for-edge-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!