For a XPages application there was the need to set a Date to a certain date in Java, off course
For this I always use the java.util.Calendar class, because it have some nice extra features.
The start is pretty straight forward, get an instance of the Calendar.
1 | Calendar cal = Calendar.getInstance(); |
Next is set the Calendar to a certain time. In the past when using the Date object, you could do it like Date date = new Date(“30-09-2015”)
The equivalent in Calendar looks like
1 | cal.set( 2015 , 9 , 30 ) |
But the result is not the same, when you print the Calendar to the console you will notice that it will be set to 30 October 2015, huh….!!
Calendar months starts at 0 and not at 1 as you might expect.
This could cause some strange issues. Let try this example
1 | cal.set( 2015 , 10 , 31 ) |
The output will be 01 December 2015, because in November there is has no 31 days.
Solution
The Calendar has some nice build in fields. For every month there is a field, like JANUARY or SEPTEMBER
In my example above the code will looks like
1 | cal.set( 2015 , Calendar.SEPTEMBER, 30 ); |
In the the console you will see the correct date, 30 September 2015
Happy coding