问题描述
在尝试将 java.util.Date
转换为 java.time.LocalDate
时,我收到以下异常。
I am getting the following exception while trying to convert java.util.Date
to 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
class?
Is there something wrong in the way I am using the ZonedDateTime
class?
根据文档,应将 java.util.Date
对象转换为 ZonedDateTime
。上述日期格式是标准日期?
As per documentation, this should convert a java.util.Date
object to ZonedDateTime
. The date format above is standard Date?
我必须在Joda时间回落吗?
Do I have to fallback on Joda time?
如果有人可以提供一些建议,那将是很棒的
If someone could provide some suggestion, it would be great.
推荐答案
将 Instant
转换为 ZonedDateTime
, ZonedDateTime
提供方法。所以
To transform an Instant
to a ZonedDateTime
, ZonedDateTime
offers the method ZonedDateTime.ofInstant(Instant, ZoneId)
. So
所以,假设你想要在默认的时区内一个 ZonedDateTime
,你的代码应该是
So, assuming you want a ZonedDateTime
in the default timezone, your code should be
ZonedDateTime d = ZonedDateTime.ofInstant(calculateFromDate.toInstant(),
ZoneId.systemDefault());
这篇关于Java8 java.util.Date转换为java.time.ZonedDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!