java year,Java中【年(year)和周年(week year)】的区别

在将日期格式化的时候,不注意的话代码中可能同时存在“yyyy-MM-dd”和“YYYY-MM-dd”两种格式,date格式为“YYYY-MM-dd”表示的是周年,date格式为“yyyy-MM-dd”表示的是年。

这两种格式是的功能是完全一样的吗?

先上代码测试一下:

import java.text.SimpleDateFormat;

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

import java.util.Date;

/**

* @author *** on 2019-12-30 21:02

*/

public class testDate {

public static void main(String[] args) {

SimpleDateFormat sdfUpperCase = new SimpleDateFormat("YYYY-MM-dd");

SimpleDateFormat sdfLowerCase = new SimpleDateFormat("yyyy-MM-dd");

Date nowDate = new Date();

System.out.println("now = " + nowDate);

System.out.println("upperCase nowDate = " + sdfUpperCase.format(nowDate));

System.out.println("lowerCase nowDate = " + sdfLowerCase.format(nowDate));

System.out.println();

LocalDateTime nowTime = LocalDateTime.now();

System.out.println("now = " + nowTime);

DateTimeFormatter dtfUpperCase = DateTimeFormatter.ofPattern("YYYY-MM-dd");

DateTimeFormatter dtfLowerCase = DateTimeFormatter.ofPattern("yyyy-MM-dd");

System.out.println("upperCase nowDate = " + nowTime.format(dtfUpperCase));

System.out.println("lowerCase nowDate = " + nowTime.format(dtfLowerCase));

}

}

结果如下:

now = Tue Dec 31 17:09:22 CST 2019

upperCase nowDate = 2020-12-31

lowerCase nowDate = 2019-12-31

now = 2019-12-31T17:09:22.904

upperCase nowDate = 2020-12-31

lowerCase nowDate = 2019-12-31

Process finished with exit code 0

显然,结果是不同的。这是为什么呢?

参考了以下两篇文章,梳理一下原因:

year 和 weak year 的区别、JAVA周年问题。

简单解释下:

A week year is in sync with a WEEK_OF_YEAR cycle.  All weeks between the first and last weeks (inclusive) have the same week year value.  Therefore, the first and last days of a week year may have different calendar yearvalues.

周年是是按每周更新的;

一年中,第一周和最后一周之间的每周的周年和当时的年份是一致的;

但是第一周和最后一周的周年可能和当时的年份不一致的。

如在2019年12月31日(星期二)这天,年是2019年,但周年就成了2020年。

具体的源码还没有细看,通过这个问题给自己的结论就是:

1、以后日期尽量使用“yyyy-MM-dd”这种格式;

2、后面可以尝试使用Java.time包获取更准确的时间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值