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

自作多情 提交于 2019-12-17 17:12:29

问题


Today some tests on a new build machine failed, where on other machines thes where ok. Looking after the problem it shows that

@Test
public void testDateTimeFormater()
{
    String result = LocalDate.of(2000,1,2)
            .format(DateTimeFormatter.ofPattern("YYYY-MM-dd"));
    Assert.assertTrue(result,result.equals("2000-01-02"));
}

Results in 'java.lang.AssertionError: 1999-01-02'

The jave version not working is

root@build02:~# java -version 
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

(OS Debian 9, Ubuntu 18.04)

where as on the developer machine the working java version is

java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

(OS Ubuntu 14.04)

Whats the problem? Is there something I can check?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/52984414/java-localdate-formatting-of-2000-1-2-error

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