4

I've got various java.util.Date objects with values of this format: 2014-01-21 10:28:57.122Z. I would like to convert them all to ZonedDateTime objects.

According to this SO question, and ZonedDateTime's ofInstant(), one way is like so:

ZonedDateTime z = ZonedDateTime.ofInstant(dateObject.toInstant(), ZoneId);

The problem is, how do I figure out what to use for the ZoneId parameter? I can't use my system time (ZoneId.systemDefault()) because my Date objects all have different timezones.

Community
  • 1
  • 1
yiwei
  • 3,384
  • 7
  • 31
  • 53
  • 1
    If they end in `Z` they are UTC by definition. Can you [edit] to show us the code where you create / parse for these objects? – durron597 Aug 20 '15 at 20:38

1 Answers1

7

Your java.util.Date object does not have a time zone. Dates are always stored internally in UTC.

When you parse a text string into a Date object, the parser applies a time zone, either as given in the text, as a parameter to the parser, or by default.

When you display a Date object, the formatter will generate the text as requested, in the time zone requested, whether the time zone is displayed or not.

So, without time zone information in the Date object, you must specify the time zone you want when converting to ZonedDateTime.

Better yet, parse the text directly to a ZonedDateTime, so it can remember the original time zone from the text.

Andreas
  • 138,167
  • 8
  • 112
  • 195