日历设置年度问题

时间:2011-11-24 22:53:43

标签: java date calendar

我尝试了以下代码:

Calendar c1 = Calendar.getInstance();
c1.set(Calendar.YEAR, 0);
c1.set(Calendar.DAY_OF_YEAR, 1);
Date d1 = c1.getTime();

Calendar c2 = Calendar.getInstance();
c2.setTime(d1);
c2.set(Calendar.YEAR, 2001);
c2.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(c2.getTime().toString());

Calendar c3 = Calendar.getInstance();
c3.set(Calendar.YEAR, 2000);
c3.set(Calendar.DAY_OF_YEAR, 1);
Date d2 = c3.getTime();

Calendar c4 = Calendar.getInstance();
c4.setTime(d2);
c4.set(Calendar.YEAR, 2001);
c4.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(c4.getTime().toString());

结果是:

Wed Jan 01 23:47:00 CET 2001
Mon Jan 01 23:47:00 CET 2001

有什么问题?我不应该以这种方式使用日历来设置YEAR吗?

2 个答案:

答案 0 :(得分:15)

这一年与时代有关。通过将年份设置为小于或等于0的值,日历会通过切换时代(从AD到BC或从BC到AD)自动更正这一点。从其他字段可以更好地了解此行为。例如。如果你将月份设置为负值,则年份会相应减少。

这些更正不是单独进行的,而是一次性完成,通常是在您致电getTime()以读出结果日期时。

Calendar c1 = Calendar.getInstance(); // August  16th, 2012 AD
c1.set(Calendar.YEAR, 0);             // August  16th,    0 AD
c1.set(Calendar.DAY_OF_YEAR, 1);      // January  1st,    0 AD
Date d1 = c1.getTime();               // January  1st,    1 BC (corrected)

Calendar c2 = Calendar.getInstance();
c2.setTime(d1);
c2.set(Calendar.YEAR, 2001);          // January  1st, 2001 BC
c2.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(c2.getTime());     // prints "Wed Jan 01 05:35:00 CET 2001"
                                      // because 01/01/2001 BC was a Wednesday

因此,不必将年份设置为2001,而是将其设置为-2000(因为第0年根本不存在)。或者你可以明确地设定时代:

c2.set(Calendar.ERA, GregorianCalendar.AD);

另一种解决此“错误”的方法是读出设置完整日期之前的时间:

Calendar c1 = Calendar.getInstance(); // August  16th, 2012 AD
c1.set(Calendar.YEAR, 0);             // August  16th,    0 AD
c1.set(Calendar.DAY_OF_YEAR, 1);      // January  1st,    0 AD
c1.set(Calendar.YEAR, 2001);          // January  1st, 2001 AD
System.out.println(c1.getTime());     // prints the expected date

要输出日期时代,您可以在SimpleDateFormat的模式中使用“G”:

new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy G").format(c2.getTime())
// "Wed Jan 01 05:35:00 CET 2001 BC"

答案 1 :(得分:3)

在这两种情况下,在打印输出之前,您将年份设置为2001.在这两种情况下,输出都反映了该年份。你期待不同的输出吗?