Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Timezone why different timezone give same value in millisec

Tags:

java

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.

like image 842
user84592 Avatar asked Mar 26 '12 05:03

user84592


People also ask

Does date now () depend on TimeZone?

Yes, Date. now() will give you the same UTC timestamp independent of your current timezone. Such a timestamp, rather a point in time, does not depend on timezones. The Java equivalent new Date() gives you the exact same thing.

What is TimeZone offset in Java?

ZoneOffset extends ZoneId and defines the fixed offset of the current time-zone with GMT/UTC, such as +02:00. This means that this number represents fixed hours and minutes, representing the difference between the time in current time-zone and GMT/UTC: LocalDateTime now = LocalDateTime.

What does TimeZone getDefault return?

TimeZone getDefault() Method in Java with Examples Return Value: The method returns the default TimeZone of the host.


2 Answers

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.

like image 130
Jon Skeet Avatar answered Oct 13 '22 18:10

Jon Skeet


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.

like image 6
zsxwing Avatar answered Oct 13 '22 18:10

zsxwing