JDK1.8中LocalDateTime 与 Date 通过 Instant(瞬时 即时) 进行互转
具体可用查看 Date 与 LocalDateTime 源码
主要方法:
// Date 源码主要方法
public static Date from(Instant instant) {
try {
return new Date(instant.toEpochMilli());
} catch (ArithmeticException ex) {
throw new IllegalArgumentException(ex);
}
}
public Instant toInstant() {
return Instant.ofEpochMilli(getTime());
}
//LocalDateTime 源码主要方法
public ZonedDateTime atZone(ZoneId zone) {
return ZonedDateTime.of(this, zone);
}
default Instant toInstant() {
return Instant.ofEpochSecond(toEpochSecond(), toLocalTime().getNano());
}
Date 源码
Date.from()
public static Date from(Instant instant) {
try {
return new Date(instant.toEpochMilli());
} catch (ArithmeticException ex) {
throw new IllegalArgumentException(ex);
}
}
demo
// LocalDateTime 转 Date
LocalDateTime localDateTime = LocalDateTime.now();
Date date2 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(date2));
// Date 转 LocalDate
Date date3 = new Date();
LocalDateTime localDateTime1 =
date3.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(localDateTime1);
String 转 Date
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// String 转 Date
Date date6 = format.parse("2022-06-14 15:28:04");
System.out.println("SimpleDateFormat String 转 Date :" + date6);
// 时间戳(毫秒 ) 转 日期格式
// 时间戳转 Date 直接 new Date(时间戳)
Date date5 = new Date(1655192442000L)
// Date 转 String
String data5Str = format.format(date5);
System.out.println("时间戳:"+data5Str);



