user84592
user84592

Reputation: 4882

Java: Timezone why different timezone give same value in millisec

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.

Upvotes: 13

Views: 16149

Answers (3)

zsxwing
zsxwing

Reputation: 20826

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.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 24

kandarp
kandarp

Reputation: 5047

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.

Upvotes: 1

Related Questions