简体   繁体   中英

How to set java.time.LocalDate using (the value of) an java.util.Date?

I use the Java 8 DatePicker (and I like it).

This Class uses java.time.LocalDate . Persistence on the other hand uses (exclusively in MAR 2014) java.util.Date . LocalDate2Date is involved but doable (see below) but I can't find a way to do Date2LocalDate.

....
entityClassFromDatabase.setDate2b(LocalDate2Date(datepicker.getvalue()));
....
}

private java.util.Date LocalDate2Date(LocalDate localDate) {
    [validation code omitted]
    ChronoLocalDateTime cldt = localDate.atStartofDay();
    Instant instant = cldt.toInstant(ZoneOffset.from(Instant.now().atZone(ZoneId.systemDefault())));
    return Date.from.(instant);
}

What I need is something like;

datepicker.setvalue(Date2LocalDate(entityClassFromDatabase.getDate2b());

I have seen answers that suggest new LocalDate(date); and variants, but these do not work;

Latest effort was 'conversion' via java.time.Instant but although the 'instant' used in LocalDate2Date prints out identical to the instant used below:

Instant instant = entityClassFromDatabase.getDate2b.toinstant();
LocalDateTime xx = LocalDateTime.from(instant);

throws exception below:

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-03-27T23:00:00Z of type java.time.Instant

I'm lost

Use:

public LocalDate dateToLocalDate(final Date date)
{
    return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault())
        .toLocalDate();
}

However, as mentioned, this has no timezone information anymore.

The javadoc says about this method:

Obtains an instance of LocalDateTime from an Instant and zone ID.

This creates a local date-time based on the specified instant. First, the offset from UTC/Greenwich is obtained using the zone ID and instant, which is simple as there is only one valid offset for each instant. Then, the instant and offset are used to calculate the local date-time.

您还可以传入您的时区作为 -

LocalDateTime localDateTime = LocalDateTime.from(new Date().toInstant().atZone(ZoneId.of("UTC")));

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