java.util.Date ⇔ java.time.LocalDateTime conversion

Note

A note on converting between java.util.Date and java.time.LocalDateTime.

Convert from java.util.Date to java.time.LocalDateTime

    /**
     *Convert from Date to LocalDateTime
     * @return
     */
    public LocalDateTime toLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
        return zonedDateTime.toLocalDateTime();
    }

If the execution environment and the locale you want to get are different in the Web application etc., specify the locale you want to get the ZoneId when converting to ZonedDateTime.

//        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("JST")));

Convert from LocalDateTime to Date

    /**
     *Convert from LocalDateTime to Date
     * @param localDateTime
     * @return
     */
    public Date toDate(LocalDateTime localDateTime) {
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        Instant instant = zonedDateTime.toInstant();
        return Date.from(instant);
    }

If the execution environment and the locale you want to acquire are different in the Web application etc., LocalDateTime does not hold the locale information, so you need to specify the locale at the time of acquiring the instance.

//        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of(ZoneId.SHORT_IDS.get("JST")));

Recommended Posts

java.util.Date ⇔ java.time.LocalDateTime conversion
Java-forced conversion
Java 8 LocalDateTime type conversion stuff (String, java.util.Date)