Java LocalDate Formatting of 2000-1-2 error [duplicate]

丶灬走出姿态 提交于 2019-11-28 02:24:39

You most probably do not want the format "YYYY-MM-dd", but instead "yyyy-MM-dd".

"Y" is the week-based year, which is locale-dependent. January 2, 2000 may belong to the week-based year 1999 in some locales and to the week-based year 2000 in some other locales.

"y" is the year-of-era, that is what is normally used as calendar year.

When I just print the toString() method of the result, it becomes pretty obvious that the formatting passed to the DateTimeFormatter is the problem:

public static void main(String[] args) {
    String result = LocalDate.of(2000,1,2)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    System.out.println(result.toString());

    String wrongResult = LocalDate.of(2000,1,2)
            .format(DateTimeFormatter.ofPattern("YYYY-MM-dd"));
    System.out.println(wrongResult.toString());
}

This prints

2000-01-02
1999-01-02

So maybe the older Java version did not recognize the difference, but the newer one does. For an explanation, have a look at the answer by @ThomasKläger.

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