A note on Java's Calendar set() method

Remember that the Calendar's internal fields include year, month, date, hour, minutes, seconds, milliseconds and time zone. Whenever you are calling a set() method with multiple fields, like set(year, month, date), it will not affect the rest of the fields.

Remember that there is no set() method with multiple fields available to set the milliseconds. If you would like to set the milliseconds, you must use set(Calendar.MILLISECOND, value). Likewise, if you are planning to set all the fields, its a good idea to reset all the fields using clear() method. This will clear milliseconds as well.

Most of the times, millisecond field may not be of interest to you. But if you are going to use the UTC milliseconds, by calling getTimeInMillis(), then make sure you set the right values for milliseconds as well.


Anonymous said…
Nice post. it helped me set MS in my calendar.

One more note on set() (and the constructor) is that for the month field 0 is january not 1. seems a bit odd to me but thats how they wrote it.
Anonymous said…
boy - not knowing about that millisecond set method messed me up but good. How overly-complicated can they make it? Anyway? You can't even pass a date into it and instantiate it in one line! Can you say "Lamo"?
Thanks for the post - it was a life-saver 4 me.
There exist to be more of the possible values and instances for the students and hopefully for t he future these would almost amount to better understanding of interest.

Popular posts from this blog

The mysterious ORA-03111 error

Note on allocationSize parameter of @SequenceGenerator while using JPA

Creating a Collection with a single element