1

I have this piece of code for a client in Eastern time zone:

public DateTime getActivityDate() {
    return new DateTime(activityDate, DateTimeZone.UTC).minusHours(5);
}

The client was reporting it was working until the time change back in November. Now they are reporting they are seeing the times as " 1 hour ahead of Eastern time zone."

Is there any way I can get this working for both davelight savings time and standard time instead of hardcoding it as minusHours(5) and minusHours(6)?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Mdjon26
  • 2,145
  • 4
  • 19
  • 29
  • There are [at least 4 timezones](https://en.wikipedia.org/wiki/EST#Time) which use the abbreviation "EST". Don't use three-letter abbreviations, use IANA abbreviations, like "America/New York". – Andy Turner Dec 19 '16 at 15:58
  • 1
    One thing is strange. How do you justify to subtract 5 or SIX hours when speaking about Eastern time zone? New York - time has offsets either -05 or -04 but not -06. Other zones mentioned in link given by @Andy Turner are even completely off for the offsets you want. – Meno Hochschild Dec 19 '16 at 16:02

2 Answers2

3

Yes, please use the appropriate timezone identifier for New York - time:

return new DateTime(activityDate, DateTimeZone.forID("America/New_York"));

By the way: It is a wrong idea to do time arithmetic like minusHours(5) here in order to take tz offsets into account. What you are doing, is also changing the instant/moment given by activityDate and not just changing the local representation in appropriate timezone. Example showing the difference between your code and my proposal:

System.out.println(new DateTime(new Date(), DateTimeZone.forID("America/New_York"))); 
// 2016-12-19T11:05:58.507-05:00

System.out.println(new DateTime(new Date(), DateTimeZone.UTC).minusHours(5)); 
// 2016-12-19T11:05:58.573Z

We have same "local" representations but different offsets (-05 versus Z=+00) resulting in different instants. Only my proposal yields correct local time (for New York) AND correct instant.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Wouldn't I still have to hardcode the minus 5 or 6 hours for this though? – Mdjon26 Dec 19 '16 at 15:50
  • @Mdjon26 Oh no, don't use hard-coding. The given zone will automatically convert given `activityDate` to a proper local representation within `DateTime`, either UTC-05 (in winter) or UTC-04 (in summer). No further action needed. – Meno Hochschild Dec 19 '16 at 15:52
1

If you are using org.joda.time.DateTime :

public static final DateTime getEasternUSLocalDateTime(DateTime pDateTimeUtc) {

    // Convert the Date
    DateTime convertedDate  = originalDate.withZone(DateTimeZone.forID("America/New_York"));
    // Return the localTime associated with the timeZone
    return convertedDate.toLocalDateTime();
}
TheBakker
  • 2,852
  • 2
  • 28
  • 49