LocalDateTime转Date

witmy

关注

阅读 103

2023-02-20


LocalDateTime转Date

LocalDateTime localDateTime = LocalDateTime.now();

Date date = Date.from( localDateTime.atZone( ZoneId.systemDefault()).toInstant());

System.out.println(date);

Date转LocalDateTime

Date todayDate = new Date();

LocalDateTime ldt = todayDate.toInstant()
.atZone( ZoneId.systemDefault() )
.toLocalDateTime();

System.out.println(ldt);

再省事点就写一个DateUtil类

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {

public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}

public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}

public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}

public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}


精彩评论(0)

0 0 举报