Y returns 2012 while y returns 2011 in SimpleDateFormat

前端 未结 5 1008
粉色の甜心
粉色の甜心 2020-11-22 01:39

I wonder why \'Y\' returns 2012 while \'y\' returns 2011 in SimpleDateFormat:

System.out.println(new SimpleDateFormat(\"Y\").format(new Date()))         


        
5条回答
  •  攒了一身酷
    2020-11-22 02:21

    I convert a date back and forth - you would expect the same year when you do this.

    Notice how it advances one!

    This is bad: YYYY!

    You can run it here.

    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.text.ParseException;
    import static java.lang.System.out;
    class Playground {
        public static Date convertYYYYMMDDStr(String s) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date result = null;
            try {
                result = sdf.parse(s);
            } catch(ParseException e) {
                e.printStackTrace();
            }
            return result;
        }
        public static String formatDateToStrWithSDF(Date d, SimpleDateFormat s) {
            return s.format(d);
        }
        public static void main(String[ ] args) {
            // DON'T DO. Use yyyy instead of YYYY
            SimpleDateFormat sdfdmy = new SimpleDateFormat("dd-MM-YYYY"); 
            String jan1st2020sb = "2020-01-01";
            Date jan1st2020d = convertYYYYMMDDStr(jan1st2020sb);
            String jan1st2020sa = formatDateToStrWithSDF(jan1st2020d, sdfdmy);
            out.println(jan1st2020sb);
            out.println(jan1st2020d);
            out.println(jan1st2020sa);
            String dec31st2020sb = "2020-12-31";
            Date dec31st2020d = convertYYYYMMDDStr(dec31st2020sb);
            String dec31st2020sa = formatDateToStrWithSDF(dec31st2020d, sdfdmy);
            out.println(dec31st2020sb);
            out.println(dec31st2020d);
            out.println(dec31st2020sa);
        }
    }
    

    This is good: yyyy

提交回复
热议问题