Strange error in Java format time

The project recently reported a bug, the end time is less than the start time. It took a long time to find out that it was an error when formatting time.
Generally we format time,
SimpleDateFormat df = new SimpleDateFormat ("YYYY-MM-DD");
There are many time formats here, YYYY and yyyy are very different, first look at the code:
SimpleDateFormat df = new SimpleDateFormat (" YYYY-MM-DD ”);
String d =“ 2020-01-02 ”;
try {
Date date = df.parse (d);
System.out.println (date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} The
output is: Sun Dec 29 00:00:00 CST 2019
magic! ! ! ! How did it become 2019 after formatting in 2020? ? ?
It turns out that this is a bug in Java. When formatting time, y is Year, and Y represents Week year. The capitalized YYYY will be the year of the week where the date needs to be formatted, that is, which year is the week where January 2, 2020 belongs, and note that the week starts on Sunday, so the year of January 2 is still 2019.
To avoid such errors, it is best to use yyyy when formatting time. code show as below:
SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-DD”);
String d = “2020-01-02”;
try {
Date date = df.parse(d);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
输出结果:Thu Jan 02 00:00:00 CST 2020

Published 6 original articles · liked 0 · visits 354

Guess you like

Origin blog.csdn.net/weixin_44863376/article/details/103883738