I just encountered a strange behaviour with the GregorianCalendar class, and I was wondering if I really was doing something bad.
This only appends when the initiali
I'm sure it is not wanted behavior. I'm just equally sure no one really thought that use case through when they made the class. The fact of the matter is that Calendar has a very big problem with internal state and how it manages all of the potential transitions in all the set methods.
If you can't use JodaTime or JSR-310 in your project, unit test heavily when using the Calendar class. As you can see in this case Calendar code behaves differently depending on what day of the month (or what time of the day) you run the code.
I should like to contribute the modern answer.
ZonedDateTime endOfFebruary2010 = LocalDate.of(2010, Month.MARCH, 1)
.atStartOfDay(ZoneId.systemDefault())
.minusNanos(1);
System.out.println(endOfFebruary2010);
Running in my time zone this prints:
2010-02-28T23:59:59.999999999+01:00[Europe/Copenhagen]
The printout is the same no matter the time of year and month you run it. The dependency on time zone may be unfortunate, but can be mended by specifying which time zone you want, for example ZoneId.of("Asia/Oral")
. I am using and recommending java.time
, the modern Java date and time API.
If you indispensably need an old-fashioned java.util.Date
object (and only in this case), convert:
Date oldFashionedDate = Date.from(endOfFebruary2010.toInstant());
System.out.println(oldFashionedDate);
Sun Feb 28 23:59:59 CET 2010
If you only needed a count of days in some month (this was asked in a duplicate question):
YearMonth ym = YearMonth.of(2011, Month.FEBRUARY);
int numDays = ym.lengthOfMonth();
System.out.println(numDays);
28
As I understand, your real question was:
…I was wondering is this really was the wanted behaviour. Any thoughts ?
I strongly believe that it is wanted behaviour that the no-arg GregorianCalendar
constructor returns the current day and the current time of day. And that Calender.set()
only sets the fields that you explicitly set and tries to keep other fields unchanged. And that February 31, 2010 overflows into March without any sign of error because there were only 28 days in the month. The combination of these design decisions leads me to the inevitable conclusion: the behaviour you observed is by design.
If you think this is a poor design, we are many that agree with you. This was also why the replacement for Calendar
and GregorianCalendar
came out with java.time
four years ago now. You will never need to use Calendar
again.
java.time
works nicely on Java 7. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Calendar starts with current day - 31 may 2010 in your example. When you set month to February, date changes to 31 February 2010 which normalized to 3 March 2010, so cal.getActualMaximum(Calendar.DAY_OF_MONTH) returns 31 for March.
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2010);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 31);
System.out.println(c.getTime());
c.set(Calendar.MONTH, Calendar.FEBRUARY);
System.out.println(c.getTime());
output:
Mon May 31 20:20:25 GMT+03:00 2010
Wed Mar 03 20:20:25 GMT+03:00 2010
To fix you code, you can add cal.clear(); or set day 1..28 before setting month
The problem is that DAY_OF_MONTH
is 1-based, day 0
is one day less!
It is getting the actual maximums of the current date/time. May has 31 days which is 3 more than 28 February and it will thus shift to 3 March.
You need to call Calendar#clear() after obtaining/creating it:
GregorianCalendar cal = new GregorianCalendar();
cal.clear();
// ...
This results in:
Sun Feb 28 23:59:59 GMT-04:00 2010
(which is correct as per my timezone)
As said in one of the answers, the java.util.Calendar
and Date
are epic failures. Consider JodaTime when doing intensive date/time operations.
The reason should be, that MONTH has an enumeration-like logical structure. You can easyly fill and read Arrays/Collections/Lists. Due to internationalization it has to be enumeratable (indirect access). DAY is just an direct accessible Integer. That's the difference.