本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接
问题:Java8里面java.util.Date 转成 java.time.ZonedDateTime
尝试将java.util.Date转成java.time.LocalDate的过程中,出现了下面的异常
java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2014-08-19T05:28:16.768Z of type java.time.Instant
代码如下:
public static Date getNearestQuarterStartDate(Date calculateFromDate){
int[] quaterStartMonths={1,4,7,10};
Date startDate=null;
ZonedDateTime d=ZonedDateTime.from(calculateFromDate.toInstant());
int frmDateMonth=d.getMonth().getValue();
}
我使用ZonedDateTime类的方式有问题吗?
根据文档,这应该可以将java.util.Date对象转换为ZonedDateTime的。以上日期格式是标准日期吗?
我必须用Joda时间吗?
如果有好心人能提供一些建议,那就太好了。
回答一
为了将一个时刻转换成一个ZonedDateTime, ZonedDateTime提供了ZonedDateTime.ofInstant(Instant, ZoneId)方法
因此,假如你希望在默认时区中使用ZonedDateTime,那么您的代码应该是这样的
ZonedDateTime d = ZonedDateTime. ofinstant (calculateFromDate.toInstant(),
ZoneId.systemDefault ());
回答二
答案不适合我在Java 10存储UTC的util.Date。
Date.toInstant()似乎是将EpochMillis转换为服务器的本地时区。
ZDT.ofInstant(instant, zoneId)和instant. atzone (zoneId)似乎只是给某个时刻的TZ打标签,但它已经很混乱了。
我无法找到一种方法来防止Date.toInstant()和系统时区的UTC时间搞乱。
我发现解决这个问题的唯一方法是执行sql。时间戳类:
new java.sql.Timestamp(date.getTime()).toLocalDateTime()
.atZone(ZoneId.of("UTC"))
.withZoneSameInstant(desiredTZ)
回答三
要从 Date中获取ZonedDateTime,你可以使用:
calculateFromDate.toInstant().atZone(ZoneId.systemDefault())
然后,如果需要LocalDate,可以调用toLocalDate方法。如果想要了解更多请看:Convert java.util.Date to java.time.LocalDate
文章翻译自Stack Overflow:stackoverflow.com/questions/2…