Java – Calendar setting year problem

I tried the following code:

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());

The result is:

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

What's wrong? Shouldn't I use my calendar to set year in this way?

Solution

This year is relative to the times By setting the year to a calendar less than or equal to 0, the calendar will be automatically corrected by switching the era (from ad to BC or from BC to AD) This behavior is better known from other fields For example If the month is set to a negative value, the year is reduced accordingly

These corrections are not done separately, but are done at once, usually when you call gettime () to read the generated date

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

Therefore, instead of setting the year to 2001, you must set it to - 2000 (because year 0 does not exist at all) Or you can set the times explicitly:

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

Another way to solve this "error" is not to read the time before the full date setting:

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

To output the age of the date, you can use "g" in the schema of simpledateformat:

new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy G").format(c2.getTime())
// "Wed Jan 01 05:35:00 CET 2001 BC"
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>