Date、LocalDate、LocalDateTime之间的转换和计算

// 01. java.util.Date --> java.time.LocalDateTime
public void date2LocalDateTime() {
    Date date = new Date();
    Instant instant = date.toInstant();
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
}

// 02. java.util.Date --> java.time.LocalDate
public void date2LocalDate() {
    Date date = new Date();
    Instant instant = date.toInstant();
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
    LocalDate localDate = localDateTime.toLocalDate();
}

// 03. java.util.Date --> java.time.LocalTime
public void date2LocalTime() {
    Date date = new Date();
    Instant instant = date.toInstant();
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
    LocalTime localTime = localDateTime.toLocalTime();
}


// 04. java.time.LocalDateTime --> java.util.Date
public void localDateTime2Date() {
    LocalDateTime localDateTime = LocalDateTime.now();
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDateTime.atZone(zone).toInstant();
    Date date = Date.from(instant);
}


// 05. java.time.LocalDate --> java.util.Date
public void localDate2Date() {
    LocalDate localDate = LocalDate.now();
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
    Date date = Date.from(instant);
}

// 06. java.time.LocalTime --> java.util.Date
public void localTime2Date() {
    LocalTime localTime = LocalTime.now();
    LocalDate localDate = LocalDate.now();
    LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDateTime.atZone(zone).toInstant();
    Date date = Date.from(instant);
}

// 07、计算2个 LocalDate 之间相差多少天,如果是同一天则会返回0
public long differLocalDateDay(LocalDate before,LocalDate after){
    LocalDate before = LocalDate.of(2017, 12, 15);
    LocalDate after = LocalDate.of(2017, 12, 15);
    long differDay = after.toEpochDay() - before.toEpochDay();
    return Math.abs(differDay);
}

// 08、就算2个 LocalDateTime 之间相差多少天,如果是同一天返回0
public long differDayOfLocalDateTime(){
    LocalDateTime first = LocalDateTime.of(2018, 8, 15, 1, 1, 1);
	LocalDateTime second = LocalDateTime.of(2018, 9, 16, 1, 5, 1);
    return Duration.between(first, second).toDays();
}

你可能感兴趣的:(java工具)