2014-12-23 16 views
2

我的理解是,PST與GMT/UTC相差8小時。但是,當我打印出來時,我發現只有7小時的差異。你能解釋我在這裏做錯了嗎?打印GMT和PST時間戳僅顯示7小時的差異

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); 
    Date date = sdf1.parse("2014-05-01 13:31:03.7"); 

    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmssS"); 
    df.setTimeZone(TimeZone.getTimeZone("PST")); 
    System.out.println(df.format(date)); 
    df.setTimeZone(TimeZone.getTimeZone("GMT")); 
    System.out.println(df.format(date)); 
    df.setTimeZone(TimeZone.getTimeZone("UTC")); 
    System.out.println(df.format(date)); 

打印:

20140501_1331037 
20140501_2031037 
20140501_2031037 
+2

避免在時區中使用3或4個字母代碼。這些代碼既不標準也不唯一。使用[適當的時區名稱](http://en.m.wikipedia.org/wiki/List_of_tz_database_time_zones)。這些名稱主要是大陸,斜線和城市或地區的組合。對於美國西海岸,「美國/洛杉磯」。對於加拿大東部,「美國/蒙特利爾」。 –

+2

如果使用Joda-Time或java.time而不是java.util.Date/.Calendar,則處理時區會更容易。 –

+0

爲了記錄,我將我的代碼轉換爲使用Joda時間,如上所示。 – MedicineMan

回答

7

我假設你正在做的PST夏天/一大跳節省時間,當它是GMT + 7。嘗試冬季的中間。

http://wwp.greenwichmeantime.co.uk/time-zone/usa/pacific-time/

什麼時候太平洋時間更改爲夏令時?

在美國和加拿大大多數省份的大多數州中,大多數州的地區爲 ,都遵守夏令時(DST) 。在DST期間,PT或PDT比格林威治標準時間晚7小時 時間(GMT-7)。

在太平洋時間夏季月份後,太平洋標準時間(PST)或(GMT-8)向後移動1小時至美國 。

時間表對於採用日光 節約時間,美國的狀態是:

凌晨2時的第二個星期日在三月份就 十一月的第一個星期日

凌晨2時。

6

你在這裏沒有做任何不正確的事。如果您在到輸出格式添加的時區:

SimpleDateFormat df = new SimpleDateFormat("HH mm ssS Z z"); 

,你可以看到輸出實際上是PDT(夏令時),而不是PST(定期)

10 31 037 -0700 PDT 
17 31 037 +0000 GMT 
17 31 037 +0000 UTC 
12 31 037 -0500 EST 
17 31 037 +0000 GMT 

五月是在夏令時。

2

這是使用Joda-Time 2.6的解決方案。

String inputRaw = "2014-05-01 13:31:03.7"; 
String input = inputRaw.replace(" ", "T"); // Adjust input to comply with the ISO 8601 standard. 
DateTimeZone zone = DateTimeZone.UTC; 
DateTime dateTime = new DateTime(input, zone); // The input lacks an offset. So specify the time zone by which to interpret the parsed input string. The resulting DateTime is then adjusted to the JVM’s current default time zone. So, *two* time zones were used in this line of code, one explicit, the other implicit. 
DateTime dateTimeUtc = dateTime.withZone(DateTimeZone.UTC); // Adjust to UTC. 
DateTime dateTimeLosAngeles = dateTime.withZone(DateTimeZone.forID("America/Los_Angeles")); // Adjust to US west coast time zone. DST is automatically applied as needed. 
DateTime dateTimeKolkata = dateTime.withZone(DateTimeZone.forID("Asia/Kolkata")); // Adjust to India time, five and a half hours ahead of UTC. 

所有這些DateTime對象表示宇宙歷史時間軸中的相同時刻。每個人都有不同的時間(可能有不同的日期),以適應特定地區人們可能看到的時鐘上的「牆上時間」。