震驚!java中日期格式化的大坑!

前言

我們都知道在java中進行日期格式化使用simpledateformat。通過格式 yyyy-MM-dd 等來進行格式化,但是你知道其中微小的坑嗎?

yyyy 和 YYYY

示例代碼

    @Test
    public void testWeekBasedYear() {
        Calendar calendar = Calendar.getInstance();
        // 2019-12-31
        calendar.set(2019, Calendar.DECEMBER, 31);
        Date strDate1 = calendar.getTime();
        // 2020-01-01
        calendar.set(2020, Calendar.JANUARY, 1);
        Date strDate2 = calendar.getTime();
        // 大寫 YYYY
        SimpleDateFormat formatYYYY = new SimpleDateFormat("YYYY/MM/dd");
        System.out.println("2019-12-31 轉 YYYY/MM/dd 格式: " + formatYYYY.format(strDate1));
        System.out.println("2020-01-01 轉 YYYY/MM/dd 格式: " + formatYYYY.format(strDate2));
        // 小寫 YYYY
        SimpleDateFormat formatyyyy = new SimpleDateFormat("yyyy/MM/dd");
        System.out.println("2019-12-31 轉 yyyy/MM/dd 格式: " + formatyyyy.format(strDate1));
        System.out.println("2020-01-01 轉 yyyy/MM/dd 格式: " + formatyyyy.format(strDate2));
    }

輸出的結果

2019-12-31 轉 YYYY/MM/dd 格式: 2020/12/31
2020-01-01 轉 YYYY/MM/dd 格式: 2020/01/01
2019-12-31 轉 yyyy/MM/dd 格式: 2019/12/31
2020-01-01 轉 yyyy/MM/dd 格式: 2020/01/01

卧槽?2019變成2020了?

YYYY 是怎麼做到的呢

Java’s DateTimeFormatter pattern “YYYY” gives you the week-based-year, (by default, ISO-8601 standard) the year of the Thursday of that week.
下面就是用YYYY格式化代碼

12/29/2019 將會格式化到2019年 這一周還屬於2019年
12/30/2019 將會格式化到2020年 這一周已經屬於2020年
看字說話YYYY,week-based year 是 ISO 8601 規定的。
2019-12-31號這一天,按周算年份已經屬於2020年了,格式化之後就變成2020年,後面的月份日期不變。

dd和DD

示例代碼

  private static void tryit(int Y, int M, int D, String pat) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pat);
        LocalDate         dat = LocalDate.of(Y,M,D);
        String            str = fmt.format(dat);
        System.out.printf("Y=%04d M=%02d D=%02d " +
            "formatted with " +
            "\"%s\" -> %s\n",Y,M,D,pat,str);
    }
    public static void main(String[] args){
        tryit(2020,01,20,"MM/DD/YYYY");
        tryit(2020,01,21,"DD/MM/YYYY");
        tryit(2020,01,22,"YYYY-MM-DD");
        tryit(2020,03,17,"MM/DD/YYYY");
        tryit(2020,03,18,"DD/MM/YYYY");
        tryit(2020,03,19,"YYYY-MM-DD");
    }

輸出結果

Y=2020 M=01 D=20 formatted with "MM/DD/YYYY" -> 01/20/2020
Y=2020 M=01 D=21 formatted with "DD/MM/YYYY" -> 21/01/2020
Y=2020 M=01 D=22 formatted with "YYYY-MM-DD" -> 2020-01-22
Y=2020 M=03 D=17 formatted with "MM/DD/YYYY" -> 03/77/2020
Y=2020 M=03 D=18 formatted with "DD/MM/YYYY" -> 78/03/2020
Y=2020 M=03 D=19 formatted with "YYYY-MM-DD" -> 2020-03-79

這裡的大寫的DD代表的是處於這一年中那一天,不是處於這個月的那一天,但是dd就沒有問題。

結論

格式化日期一定要選用 yyyy-MM-dd哦!

Tags: