解析来自不同时区的时间戳字符串

时间:2014-09-19 12:48:47

标签: java jodatime

我在GMT中有一个带时间戳的字符串。我想将其转换为EST中的DateTime对象。 E.g如果字符串有:
final String gmtTime = "20140917-18:55:25"; // 4:55 PM GMT
我需要将其转换为:20140917-12:55:25 //美国东部时间下午12:55

所有这些尝试都失败了:

    System.out.println("Time in GMT " + DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime));

    System.out.println("Time in EST " +
    DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime).withZone(DateTimeZone.forID("America/New_York")));

输出: 格林威治标准时间2014-09-17T18:55:25.000-04:00 EST时间2014-09-17T18:55:25.000-04:00 //我期待:2014-09-17T12:55:25.000-04:00

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

约达时间

这是一个Joda-Time 2.4解决方案:

String gmtTime = "20140917-18:55:25";
DateTime dateTimeGMT =
    DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZoneUTC().parseDateTime(gmtTime);
System.out.println("Time in GMT " + dateTimeGMT); // Time in GMT 2014-09-17T18:55:25.000Z

System.out.println(
    "Time in EST "
    + DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZone(
        DateTimeZone.forID("America/New_York")
    ).print(dateTimeGMT)
); //Time in EST 20140917-14:55:25

我认为你对结果有错误的期望。 EST(更正确使用的是" America / New_York" as zone identifier)比UTC低四个小时,因此本地时间戳比UTC同一时刻的本地时间早四个小时偏移量。

另请注意,我在格式化程序上设置的时区不在解析后的DateTime - 对象上。

答案 1 :(得分:0)

@Test
public void TimeZoneTest() {

    Date now = new Date();

    String DATE_PATTERN = "yyyyMMdd-HH:mm:ss";

    DateFormat dfEST = new SimpleDateFormat(DATE_PATTERN);
    dfEST.setTimeZone(TimeZone.getTimeZone("America/New_York"));

    DateFormat dfGMT = new SimpleDateFormat(DATE_PATTERN);
    dfGMT.setTimeZone(TimeZone.getTimeZone("GMT"));

    System.out.println(dfEST.format(now));
    System.out.println(dfGMT.format(now));

}

输出是:

20140919-09:02:19
20140919-13:02:19