SimpleDateFormat in YYYY and parse and format yyyy caused the error output

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/red_sheeps/article/details/79317208

SimpleDateFormat parse method output error

In the encoding process sends a anomaly, parse method SimpleDateFormat always outputs the first day of the current year.
Carefully I found that because of the use SimpleDateFormat in the new new YYYY , instead of yyyy , specific phenomena and codes to achieve the following:
Test execution results

    @Test
    public void testYandy() {
//      String dateStr = "20180101";
        String dateStr = "2017-03-10";
        System.out.println(DateUtil.parse("yyyy-MM-dd", dateStr, Locale.getDefault()));
        System.out.println(DateUtil.parse("YYYY-MM-dd", dateStr, Locale.getDefault()));
    }
    public static java.util.Date parse(String pattern, String strDateTime,
                                       Locale locale) {
        if (strDateTime == null || pattern == null)
            return null;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale);
            formatter.setLenient(false);
            return formatter.parse(strDateTime);
        } catch (Exception e) {
            return null;
        }
    }

The method SimpleDateFormat format output error

After parse method appears above error output, and Baidu a bit, mostly resulting explanation:
YYYY is the year where the current day of week where
yyyy is the year of the current day where
the following specific situations:
format error output

    @Test
    public void testYandy2() {
        Calendar calendar = Calendar.getInstance();
        // 2014-12-26
        calendar.set(2010, Calendar.DECEMBER, 26);
        Date strDate1 = calendar.getTime();
        System.out.println(strDate1);

        SimpleDateFormat f1 = new SimpleDateFormat("YYYY-MM-dd");
        System.out.println("Result for YYYY: " + f1.format(strDate1));
        SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("Result for yyyy: " + f2.format(strDate1));
    }

to sum up

Through the above case, the second case said to be said through the different meanings YYYY and yyyy caused, but why in the first case becomes the first day of the current year of it? Baidu did not find. . Remember the time being.

Guess you like

Origin blog.csdn.net/red_sheeps/article/details/79317208