在将日期格式化的时候,不注意的话代码中可能同时存在“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包获取更准确的时间。