yiwei
yiwei

Reputation: 4190

How to convert Date to ZonedDateTime?

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.

Upvotes: 5

Views: 9421

Answers (1)

Andreas
Andreas

Reputation: 159185

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.

Upvotes: 9

Related Questions