Calendar.JANUARY is actually 0 , not 1 .
When you provide 01 for the month field in set , you actually set the month in February, so you get 02 when SimpleDateFormat displays it as MM .
When using any of the Calendar.get/set methods, you must take extra precautions to make sure that you are aware of this discrepancy between the "natural" indexing based on 1 and the more "inconvenient" Calendar 0- based indexing. Each time you get / set the month of Calendar , there is always such an opportunity to cause a serious error.
This is just one of those inconvenient designs in Calendar that leaves much to be desired. One of the better, more enjoyable date / time API libraries available there is Joda Time , so if at all possible, you might consider switching to that library.
API Links
Calendar.MONTH - "The field number for get and set , denoting the month. This is a calendar dependent value. The first month of the year [...] is JANUARY , which is 0".Calendar.set(โฆ, int month, โฆ) - " month - the value used to set the calendar field for the month . The value of the month is 0, for example, 0 for January."
In octal literals
Also note that 01 is actually an octal literal (i.e. base 8 ). You should not be used to adding 0 to integer literals ( ยง3.10.1 ), as they can cause subtle errors / errors if you are not very careful.
For example, int i = 09; is illegal Java code.
System.out.println(010);
see also
- Can I customize syntax highlighting in Eclipse to show octal literals differently?
- Octal number of literals: when? What for? Ever?
polygenelubricants
source share