java 中日期的年-月-日格式符该设置为“yyyy-MM-dd“

2年前 (2022) 程序员胖胖胖虎阿
124 0 0

年月日是用 yyyy-MM-dd、yyyy-mm-dd、yyyy-MM-DD、YYYY-MM-dd、YYYY-mm-DD???

下面给出一段测试代码:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateFormatCase {
    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(2021, Calendar.DECEMBER, 31);
        Date strDate = calendar.getTime();

        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("2021-12-31 to yyyy-MM-dd: " + fmt.format(strDate));

        fmt = new SimpleDateFormat("yyyy-mm-dd");
        System.out.println("2021-12-31 to yyyy-mm-dd: " + fmt.format(strDate));

        fmt = new SimpleDateFormat("yyyy-MM-DD");
        System.out.println("2021-12-31 to yyyy-MM-DD: " + fmt.format(strDate));

        fmt = new SimpleDateFormat("YYYY-MM-dd");
        System.out.println("2021-12-31 to YYYY-MM-dd: " + fmt.format(strDate));

        fmt = new SimpleDateFormat("YYYY-mm-dd");
        System.out.println("2021-12-31 to YYYY-mm-dd: " + fmt.format(strDate));

        fmt = new SimpleDateFormat("YYYY-mm-DD");
        System.out.println("2021-12-31 to YYYY-mm-DD: " + fmt.format(strDate));

    }
}

控制台打印输出:

2021-12-31 to yyyy-MM-dd: 2021-12-31
2021-12-31 to yyyy-mm-dd: 2021-08-31
2021-12-31 to yyyy-MM-DD: 2021-12-365
2021-12-31 to YYYY-MM-dd: 2022-12-31
2021-12-31 to YYYY-mm-dd: 2022-08-31
2021-12-31 to YYYY-mm-DD: 2022-08-365

再运行一次输出如下:

2021-12-31 to yyyy-MM-dd: 2021-12-31
2021-12-31 to yyyy-mm-dd: 2021-09-31
2021-12-31 to yyyy-MM-DD: 2021-12-365
2021-12-31 to YYYY-MM-dd: 2022-12-31
2021-12-31 to YYYY-mm-dd: 2022-09-31
2021-12-31 to YYYY-mm-DD: 2022-09-365

所以可以看到使用 yyyy-MM-dd,输出的日期才是符合事实要求的。

其他的格式为什么会出现如上所述的输出呢?

这是因为 y,Y 、 M,m 、 d,D 都分别代表了不同的意义

多运行几次上面的代码可以看出:

 (1) y 表示  year of era

           The common use of year, 1/1 always being the first day of the year.   

          Y 表示 week based year

           A concept where a week only belongs to 1 year.

          这是 ISO 8601 规定的,这个意思是只要本周跨年,那就算入下一年。

(2) M 表示月份, m 表示 分钟;

(3) d 表示月份中的天数 ,D 表示年份中的天数。

相关文章

暂无评论

暂无评论...