4.jdk8 LocalDate与Date转换

[TOC]

1.jdk8的时间api非常好用,但是为了与老的Date时间兼容,也是非常难受

1).Date -> LocalDate

    /**
     * Date -> LocalDate
     * @param date
     * @return
     */
    public LocalDate transDateToLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

2).Date -> LocalDateTime

    /**
     * Date -> LocalDateTime
     * @param date
     * @return
     */
    public static LocalDateTime transDateToLocalDateTime(Date date) {
    //    return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

3).Date -> LocalTime

  /**
     * Date -> LocalTime
     * @param date
     * @return
     */
    public LocalTime transDateToLocalTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
    }

4).LocalDate->Date

  /**
     * LocalDate->Date
     * @param localDate
     * @return
     */
    public Date transLocalDateToDate(LocalDate localDate) {
       return Date.from( localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

5).LocalDateTime -> Date

    /**
     * LocalDateTime -> Date
     * @param localDateTime
     * @return
     */
    private Date transLocalDateTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

6).LocalTime -> Date

  /**
     * LocalTime -> Date
     * @param localTime
     * @return
     */
    private Date transLocalTimeToDate(LocalTime localTime) {
        return Date.from(LocalDateTime.of(LocalDate.now(),localTime)
            .atZone(ZoneId.systemDefault()).toInstant());
    }

你可能感兴趣的:(4.jdk8 LocalDate与Date转换)