Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 java.util.Date conversion to java.time.ZonedDateTime

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 

The code is as follow:

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(); 

Is there something wrong in the way I am using the ZonedDateTime class?

As per documentation, this should convert a java.util.Date object to ZonedDateTime. The date format above is standard Date?

Do I have to fallback on Joda time?

If someone could provide some suggestion, it would be great.

like image 648
Ironluca Avatar asked Aug 19 '14 05:08

Ironluca


2 Answers

To transform an Instant to a ZonedDateTime, ZonedDateTime offers the method ZonedDateTime.ofInstant(Instant, ZoneId). So

So, assuming you want a ZonedDateTime in the default timezone, your code should be

ZonedDateTime d = ZonedDateTime.ofInstant(calculateFromDate.toInstant(),                                           ZoneId.systemDefault()); 
like image 196
JB Nizet Avatar answered Nov 14 '22 20:11

JB Nizet


To obtain a ZonedDateTime from a Date you can use:

calculateFromDate.toInstant().atZone(ZoneId.systemDefault()) 

You can then call the toLocalDate method if you need a LocalDate. See also: Convert java.util.Date to java.time.LocalDate

like image 27
assylias Avatar answered Nov 14 '22 20:11

assylias