Watch out the milliseconds in java Calendar

milliseconds  problem

If you run the following test multiple times, you get different results:

public class MyTest {

public static void main(String[] args){

    Calendar calendar = new GregorianCalendar();

    calendar.set(calendar.YEAR, 2013);
    calendar.set(calendar.MONTH, 4);
    calendar.set(calendar.DATE, 24);
    calendar.set(calendar.HOUR, 12);
    calendar.set(calendar.MINUTE, 00);
    calendar.set(calendar.SECOND, 00);      

    System.out.print("Time " + calendar.getTimeInMillis());


result : Time 1369454400208 Time 1369454400185 Time 1369454400926

When getting Instance of calendar it has been initialized with current time. And when setting year,month etc. MILLISECOND were taken from current date.

What’s more if you get a calendar instance and  use the below api

public final void set(int year, int month, int date, int hourOfDay, int minute, int second)

And then try to compare the date with any date in Database, you will not be able to get ANY result!

This is exactly what I encountered when passing some date like this to the JPA Criteria and find no clue why no result hit..


some more explanation

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s