Search code examples
javadateutc

Java Date Conversion - UTC to Local - works differently depending on the timezone


I'm experiencing a problem when converting strings to a UTC data, and then to various timezones. It appears that my program behaves differently depending on whether I convert to EST or PST. Here is my code:

    SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    utcFormat.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));

    Date date = utcFormat.parse("2014-08-18 17:00:17");

    SimpleDateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    localFormat.setTimeZone(java.util.TimeZone.getTimeZone("PST"));

    System.out.println(localFormat.format(date));

If I run the code above, here is my output:

    2014-08-18 10:00:17

This reflects a 7 hour offset from the UTC time provided: 2014-08-18 17:00:17. This is what I would have expected. Now if I change that date to 2014-11-18 17:00:17 (changed the month from August to November), here is the output produced:

    2014-11-18 09:00:17

This is fine too as far as I can tell. The output reflects an 8 hour offset from UTC, and I believe this is due to the fact that November is not in Daylight Savings time, while August is.

The problem I'm having is that the same code above works differently if I change the time zone from "PST" to "EST". When I change to EST I get the same time output no matter whether my date is in August or November.

Here is the output using EST and 2014-08-18 17:00:17

    2014-08-18 12:00:17

Here is the output using EST and 2014-11-18 17:00:17

    2014-11-18 12:00:17

In both cases, the output represents a 5 hour offset from UTC which makes sense only during November, not during August.

Can anyone explain to me what I am doing wrong?


Solution

  • From the Documentation for TimeZone

    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.

    Instead of "EST", "US/Eastern" will be much clearer as to your intent.

    These are the supported US aliases.

    • US/Alaska
    • US/Aleutian
    • US/Arizona
    • US/Central
    • US/East-Indiana
    • US/Eastern
    • US/Hawaii
    • US/Indiana-Starke
    • US/Michigan
    • US/Mountain
    • US/Pacific
    • US/Pacific-New
    • US/Samoa