frostbite
frostbite

Reputation: 648

Parsing time stamp strings from a different time zone

I have a String with timestamp in GMT. I want to convert this to a DateTime object in EST. E.g If the string has:
final String gmtTime = "20140917-18:55:25"; // 4:55 PM GMT
I need to convert this to : 20140917-12:55:25 //12:55 PM EST

All these tries failed:

    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")));

Output: Time in GMT 2014-09-17T18:55:25.000-04:00 Time in EST 2014-09-17T18:55:25.000-04:00 //I expect: 2014-09-17T12:55:25.000-04:00

Any suggestions?

Upvotes: 1

Views: 103

Answers (2)

Meno Hochschild
Meno Hochschild

Reputation: 44061

Joda-Time

Here a Joda-Time 2.4 solution:

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

I think that you have the wrong expectation regarding the result. EST (more correct to use is "America/New_York" as zone identifier) is four hours behind UTC, hence the local timestamp there is four hours earlier than the local representation of the same moment at UTC-offset.

Also note that I set the timezone on the formatter not on the parsed DateTime-object.

Upvotes: 2

David Webb
David Webb

Reputation: 492

@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));

}

And the output is:

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

Upvotes: 0

Related Questions