13

I have following code, my target is going to return GMT+0 time in millisec. But Why I always get my local timezone millisec?

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Calendar cal2 = Calendar.getInstance();
System.out.println("Time zone id is:"+cal.getTimeZone().getID()+";time in millisec:"+cal.getTimeInMillis());
System.out.println("Time zone id is:"+cal2.getTimeZone().getID()+";time in millisec:"+cal2.getTimeInMillis());

The output is
Time zone id is:GMT;time in millisec:1332740915154
Time zone id is:Europe/Helsinki;time in millisec:1332740915154

Why different Timezone give SAME value in millisec?
I suppose if it is GMT+0 then it should be different value in millisec against local time zone.

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
user84592
  • 4,750
  • 11
  • 55
  • 91
  • Whats the time zone in your system? – sgowd Mar 26 '12 at 05:55
  • What about System.currentTimeMillis();? – user84592 Mar 26 '12 at 06:11
  • My time zone is GMT+2 with summer time – user84592 Mar 26 '12 at 06:12
  • Modern comment: I recommend you don’t use `Calendar` and `TimeZone`. Those classes are poorly designed and long outdated. Instead use `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). And `ZoneId` if you need to represent time zones. – Ole V.V. Jul 10 '20 at 16:30

3 Answers3

24

Why different Timezone give SAME value in millisec?

Because that's what it's meant to do. From the documentation:

(Returns) the current time as UTC milliseconds from the epoch.

In other words, it's the value which would be in the Date returned by getTime - it doesn't depend on the time zone. If you want values which depend on the time zone, use Calendar.Get(Calendar.YEAR) etc.

Both Calendar.getTime() and Calendar.getTimeInMillis() return values representing the instant in time within the calendar, which is independent of both time zone and calendar system.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

The millisec of a Date object in Java is just the milliseconds since GMT+0 1970/01/01 00:00:00. It's independent of the Time Zone. Time Zone is a property to format the Date to a readable string.

Abdurrahman Mubeen Ali
  • 1,331
  • 1
  • 13
  • 19
zsxwing
  • 20,270
  • 4
  • 37
  • 59
  • That's not really what time zones are for; that's more like what calendars are for. Time zones are to convert between UTC and local time. – Jon Skeet Mar 26 '12 at 06:01
1

getTimeInMillis() method return the current time as UTC milliseconds from the epoch. So, you are getting same milliseconds even both calendar object has different timezone.

kandarp
  • 4,979
  • 11
  • 34
  • 43