2014-12-23 68 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对象表示宇宙历史时间轴中的相同时刻。每个人都有不同的时间(可能有不同的日期),以适应特定地区人们可能看到的时钟上的“墙上时间”。