Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

You are getting it wrong. getTimeInMillis() will give you the time independent of time-zone. If you change the time-zone on the computer clock, but still keep the same displayed time, you actually change the time independent of time-zone. Therefore, you should not use the code you provided, nor should anyone else reading this.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top