java – 日历设置YEAR问题

前端之家收集整理的这篇文章主要介绍了java – 日历设置YEAR问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试了以下代码
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?

解决方法

这一年是相对于时代的.通过将年份设置为小于或等于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,0 AD
c1.set(Calendar.YEAR,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"

猜你在找的Java相关文章