Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar class confusion

Tags:

java

calendar

I was playing with the Calendar class and got some confusing results:

    Calendar thisCal = Calendar.getInstance();
    thisCal.clear();

    thisCal.set(2012,12,8);

    System.out.println("Year is: " + thisCal.get(Calendar.YEAR));
    System.out.println("Month is: " + thisCal.get(Calendar.MONTH));
    System.out.println("Day of Month is: " + thisCal.get(Calendar.DAY_OF_MONTH));

The output:

Year is: 2013

Month is: 0

Day of Month is: 8

Confused I am!

like image 463
user973718 Avatar asked Mar 01 '26 17:03

user973718


1 Answers

The MONTH field is zero based (inherited from some POSIX API, I think). So you're setting it to the 13th month of 2012, which it interprets as the first month (with number 0) of 2013.

If you set the lenient property to false, it would throw an Exception instead.

like image 157
Michael Borgwardt Avatar answered Mar 03 '26 07:03

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!