关于日期格式yyyy-MM-dd和YYYY-MM-dd

今天写代码的时候发现了一个比较有趣的现象,在之前并没有意识到。

代码如下:

public static List<String> getBetweenDateDatas(Date start, Date end) {
		List<String> durings = new ArrayList<String>();
		Calendar tempStart = Calendar.getInstance();
		tempStart.setTime(start);
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
		Calendar tempEnd = Calendar.getInstance();
		tempEnd.setTime(end);

		while (!tempStart.after(tempEnd)) {
			String dateStr = dateFormat.format(tempStart.getTime());
			durings.add(dateStr);
			tempStart.add(Calendar.DAY_OF_YEAR, 1);
		}
		return durings;
	}
比如输入的start为'2017-12-26',end为'2018-01-05'。则会得到这样的结果:

[2017-12-26, 2017-12-27, 2017-12-28, 2017-12-29, 2017-12-30, 2018-12-31, 2018-01-01, 2018-01-02, 2018-01-03, 2018-01-04, 2018-01-05]
但事实上,如果不转化SimpleDateFormat的话,得到的日期是:
[Tue Dec 26 00:00:00 CST 2017, Wed Dec 27 00:00:00 CST 2017, Thu Dec 28 00:00:00 CST 2017, Fri Dec 29 00:00:00 CST 2017, Sat Dec 30 00:00:00 CST 2017, Sun Dec 31 00:00:00 CST 2017, Mon Jan 01 00:00:00 CST 2018, Tue Jan 02 00:00:00 CST 2018, Wed Jan 03 00:00:00 CST 2018, Thu Jan 04 00:00:00 CST 2018, Fri Jan 05 00:00:00 CST 2018]
最终的解决方法是,在某个时刻毫无预兆的突然想到了'yyyy-MM-DD',且经过验证发现,将
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
改为:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
最终得到了正确的输出。

此后查阅文档及集大家之所成,发现了原因(虽然感觉似懂非懂,因为完全不会算week year):

“YYYY format” 是 “ISO week numbering system”
“yyyy format” 是 “Gregorian Calendar”
“YYYY specifies the week of the year (ISO) while yyyy specifies the calendar year (Gregorian)"
总之,正常情况下,如果希望按照日历格式得到每天的日期字符的话,使用'yyyy-MM-dd'没错的了……吧 大笑

猜你喜欢

转载自blog.csdn.net/aleefang/article/details/79094603