Jay
Jay

Reputation: 21

Calendar.getTimeInMillis() returns different results for same instance

I have the following code and calling getTimeInMillis() on a Calendar instance. I expect the return value to be same but it returns different results between runs.

The results were coming as below which are different. What am i doing wrong and what needs to be changed?

Time 1369454400208 Time 1369454400185 Time 1369454400926

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());

}

Upvotes: 2

Views: 4650

Answers (1)

Duncan Jones
Duncan Jones

Reputation: 69339

You need to reset the milliseconds as well.

calendar.set(Calendar.MILLISECOND, 0);

Note you should use Calendar.* to access static fields, not calendar.*.

Upvotes: 13

Related Questions