笔记 java8中Date和LocalDateTime转换

/**
 * Date转换为LocalDateTime
 * @param date
 */
public static LocalDateTime date2LocalDateTime(Date date){
    Instant instant = date.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
    //ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
    ZoneId zoneId = ZoneId.of("Asia/Shanghai");
    return instant.atZone(zoneId).toLocalDateTime();
}

//LocalDateTime转换成Date
public static Date localDateTime2Date() {
    ZoneId zoneId = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.now();
    ZonedDateTime zdt = localDateTime.atZone(zoneId);

    Date date = Date.from(zdt.toInstant());
    System.out.println("LocalDateTime = " + localDateTime);
    System.out.println("Date = " + date);
    return date;
}

你可能感兴趣的:(笔记 java8中Date和LocalDateTime转换)