例子如下:
public static void main(String[] args) {
SimpleDateFormat yMd = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2019);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 29);
System.out.println("yyyy-MM-dd = " + yMd.format(calendar.getTime()));
SimpleDateFormat YMd = new SimpleDateFormat("YYYY-MM-dd");
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.YEAR, 2019);
calendar2.set(Calendar.MONTH, 11);
calendar2.set(Calendar.DAY_OF_MONTH, 29);
System.out.println("YYYY-MM-dd = " + YMd.format(calendar2.getTime()));
}
输出:
yyyy-MM-dd = 2019-12-29
YYYY-MM-dd = 2020-12-29
分析原因:
YYYY 是 week-based-year,当天所在的周属于的年份,一周从周日开始,到周六结束;只要本周跨年了,那么这周就算入下一年。所以打印2020-12-29。