Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar.getTimeInMillis() returns different results for same instance

Tags:

java

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

}
like image 265
Jay Avatar asked Nov 20 '25 17:11

Jay


1 Answers

You need to reset the milliseconds as well.

calendar.set(Calendar.MILLISECOND, 0);

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

like image 109
Duncan Jones Avatar answered Nov 23 '25 07:11

Duncan Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!