java代码如何实现LocalDateTime转Date呢?
下文笔者讲述java代码实现LocalDateTime和Date之间互相转换的方法及示例分享,如下所示
LocalDateTime和Date之间互相转换的实现思路
实现思路: 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);例:
LocalDateTime和Date互转的示例
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();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


