Calendar getTimeInMillis() is timezone-dependent?

GVillani82 picture GVillani82 · Oct 26, 2012 · Viewed 8.9k times · Source

Java: Timezone why different timezone give same value in millisec

referring to the above link I have supposed that getTimeInMillis() of Calendar class returns the number of milliseconds independently from time zone.

But using the following code:

 Calendar cal = Calendar.getInstance();
 int dateInSeconds = (int)(cal.getTimeInMillis()/1000);
 Log.i("TIME IN SECONDS: ",""+dateInSeconds);

tried,at first, to set my system clock to 10:00 and GMT+02:00

producing a certain output number. But setting system clock to 10:00 and GMT+00:00

the output number is about 7200 greater than the prior case, which correspons to about 2 hours.

Why?

Answer

GVillani82 picture GVillani82 · Oct 29, 2012

For obtaining the number of milliseconds independent to time zone I found the following solution

Instead of:

 int dateInSeconds = (int)(cal.getTimeInMillis()/1000);

I use:

 int dateInSeconds = (int)((cal.getTimeInMillis()+cal.getTimeZone().getOffset(cal.getTimeInMillis()))/1000);

it works good for me.