Reputation: 2255
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)?
Upvotes: 1
Views: 727
Reputation: 44061
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.
Upvotes: 3
Reputation: 3042
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();
}
Upvotes: 1