Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Why?

like image 776
GVillani82 Avatar asked Oct 26 '12 08:10

GVillani82


2 Answers

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.

like image 194
GVillani82 Avatar answered Oct 30 '22 01:10

GVillani82


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.

like image 40
user1537366 Avatar answered Oct 30 '22 00:10

user1537366