简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM