3

I am using ZonedDateTime for a variable in java.

I want to convert the value of the variable (default UTC timezone) into the timezone of "America/New York" such that the date remains the same.

Example 4:00 am UTC = 12:00 am EST. Add or subtract hours from the ZonedDateTime variable such that the date is not changed.

How can we achieve this conversion?

xingbin
  • 27,410
  • 9
  • 53
  • 103
harry1102
  • 81
  • 1
  • 2
  • 10
  • When you say "*date* is not changed", do you actually mean "*time* is not changed"? E.g. 7/5 at 2 AM should stay 7/5 at 2 AM. --- Or did you mean that time should be adjusted according to time zone change, but the *date* should not be changed? E.g. 7/5 at 2 AM should not be 7/4 at 10 PM, but 7/5 at 10 PM. – Andreas Oct 02 '18 at 05:39
  • I also didn’t get it. Do you want 4 AM UTC converted to 12 midnight EDT or to 4 AM EDT? Only the latter will preserve the date in all cases (date as in year, month and day of month). – Ole V.V. Oct 02 '18 at 09:58

4 Answers4

3

You can do it by converting to LocalDateTime and back to ZonedDateTime with specified time zone:

ZonedDateTime zoned = ZonedDateTime.now();
LocalDateTime local = zoned.toLocalDateTime();
ZonedDateTime newZoned = ZonedDateTime.of(local, ZoneId.of("America/New_York"));
greg
  • 1,070
  • 7
  • 4
2

If you want to combine the date from UTC and the time from EST, you can do it this way:

ZonedDateTime utc = ...

ZonedDateTime est = utc.withZoneSameInstant(ZoneId.of("America/New_York"));

ZonedDateTime estInSameDay = ZonedDateTime.of(utc.toLocalDate(), est.toLocalTime(), ZoneId.of("America/New_York"));
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

If zone information is not necessary for your UTC time, then you'd do this better using the Instant class. With an Instant object, you can easily shift to a ZonedDateTime in a specified time zone:

Instant instant = Instant.parse("2018-10-02T04:00:00.0Z");
ZonedDateTime nyTime = instant.atZone(ZoneId.of("America/New_York")); 
//2018-10-02 00:00:00
ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

keeping your date the same, I think this could work

    ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime est = utc.plusHours(5); //normally est is 5 hours ahead
Afaq Ahmed Khan
  • 2,164
  • 2
  • 29
  • 39