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

年月日是用 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 表示年份中的天数。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值