简体   繁体   English

如何将Date转换为ZonedDateTime?

[英]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 . 我有各种java.util.Date对象,其格式为: 2014-01-21 10:28:57.122Z I would like to convert them all to ZonedDateTime objects. 我想将它们全部转换为ZonedDateTime对象。

According to this SO question, and ZonedDateTime 's ofInstant() , one way is like so: 根据这个 SO问题和ZonedDateTimeofInstant() ,一种方式是这样的:

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

The problem is, how do I figure out what to use for the ZoneId parameter? 问题是,我如何找出ZoneId参数的ZoneId I can't use my system time ( ZoneId.systemDefault() ) because my Date objects all have different timezones. 我无法使用我的系统时间( ZoneId.systemDefault() ),因为我的Date对象都有不同的时区。

Your java.util.Date object does not have a time zone. java.util.Date对象具有一个时区。 Dates are always stored internally in UTC. 日期始终以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. 将文本字符串解析为Date对象时,解析器会将时区(如文本中给出的)作为参数应用于解析器,或者默认情况下。

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. 当您显示Date对象时,格式化程序将在请求的时区中生成所请求的文本,无论是否显示时区。

So, without time zone information in the Date object, you must specify the time zone you want when converting to ZonedDateTime . 因此,在没有时区信息Date对象时, 必须指定转换,当你需要的时区ZonedDateTime

Better yet, parse the text directly to a ZonedDateTime, so it can remember the original time zone from the text. 更好的是,将文本直接解析为ZonedDateTime,以便可以记住文本中的原始时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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