问题
Playing around with Calendar and TimeZone I encountered following strange behaviour.
Calendar pstCal = Calendar.getInstance(TimeZone.getTimeZone("PST"));
System.out.println("H: "+ pstCal.get(Calendar.HOUR));
At the moment of writing this post, PST time according to http://www.timeanddate.com/time/zones/pst is 1:39am. The code shown above however produces output "H: 2"
Why 2 instead of 1 ? Closer look at the Calendar instance explains the number 2: dstSavings=3600000,useDaylight=true
But what I understood so far, PST stands for Pacific Standard Time, which means time without daylight saving.
Why is Java treating PST this way and is it right or is it a BUG ? Btw this problem isn't here for EST - here it corresponds with http://www.timeanddate.com/time/zones/est.
I saw this happening for Oracle JDK 1.8.0_60 and OpenJDK 1.8.0_60 as well.
回答1:
From the javadoc:
Three-letter time zone IDs
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
Specifically, Java may have decided that "PST" was equivalent to "America/Los_Angeles" in the past, which would mean that alternated between PST and PDT for daylight saving time. They may have decided differently about "EST" for whatever reason.
As a time zone identifier, abbreviations are no good. You will still find them in common use in display values, including the abbreviations on timeanddate.com. But that doesn't mean they are interpreted in the same way by Java.
If you really want to get technical about why "EST" and "PST" are treated differently with regard to daylight saving time when interpreted by Java as time zone IDs, consider that "EST", "MST", and "HST" are still in the tzdb source data as fixed offset time zones for POSIX backward compatibility reasons. "PST" and "CST" are no longer listed in the tzdb, so Java interprets them through some other hard-coded mapping for their own backwards compatibility with Java 1.1.
回答2:
Kousalik, first the short-name is not a good way to identify a time-zone, because it's not unique; Moreover if you call useDaylightTime() on EST timezone object then it will return false whereas when you call useDaylightTime() on PST timezone object then it returns true. From this its assured that JDK considers the two time zone differently.
TimeZone esttz = TimeZone.getTimeZone("EST");
System.out.println(esttz.getDisplayName() + " "+esttz.useDaylightTime());
TimeZone psttz = TimeZone.getTimeZone("PST");
System.out.println(psttz.getDisplayName() + " "+psttz.useDaylightTime());
Returns -
Eastern Standard Time false
Pacific Standard Time true
来源:https://stackoverflow.com/questions/32627139/java-calendar-wrong-time-for-pst-time-zone