GVillani82 GVillani82 - 1 year ago 202
Android Question

Calendar getTimeInMillis() is timezone-dependent?

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.


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download