如何将Date转化为LocalDateTime
package cn.hutool.core.date;
public class LocalDateTimeUtil {
public static LocalDateTime of(Date date) {
if (null == date) {
return null;
}
if (date instanceof DateTime) {
return of(date.toInstant(), ((DateTime) date).getZoneId());
}
return of(date.toInstant());
}
}
如何将LocalDateTime、LocalDate转化为Date
对纯原生的转化方式Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()) 进行简单封装。即先使用TemporalAccessorUtil#toInstant(TemporalAccessor) 将LocalDateTime 转化为Instant (底层就是执行localDateTime.atZone(ZoneId.systemDefault()).toInstant() )
package cn.hutool.core.date;
public class TemporalAccessorUtil extends TemporalUtil{
public static Instant toInstant(TemporalAccessor temporalAccessor) {
if (null == temporalAccessor) {
return null;
}
Instant result;
if (temporalAccessor instanceof Instant) {
result = (Instant) temporalAccessor;
} else if (temporalAccessor instanceof LocalDateTime) {
result = ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault()).toInstant();
} else if (temporalAccessor instanceof ZonedDateTime) {
result = ((ZonedDateTime) temporalAccessor).toInstant();
} else if (temporalAccessor instanceof OffsetDateTime) {
result = ((OffsetDateTime) temporalAccessor).toInstant();
} else if (temporalAccessor instanceof LocalDate) {
result = ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault()).toInstant();
} else if (temporalAccessor instanceof LocalTime) {
result = ((LocalTime) temporalAccessor).atDate(LocalDate.now()).atZone(ZoneId.systemDefault()).toInstant();
} else if (temporalAccessor instanceof OffsetTime) {
result = ((OffsetTime) temporalAccessor).atDate(LocalDate.now()).toInstant();
} else {
result = toInstant(LocalDateTimeUtil.of(temporalAccessor));
}
return result;
}
}
再使用Date#from(Instant)
package java.util;
public class Date implements java.io.Serializable, Cloneable, Comparable<Date> {
public static Date from(Instant instant) {
try {
return new Date(instant.toEpochMilli());
} catch (ArithmeticException ex) {
throw new IllegalArgumentException(ex);
}
}
}
DateTime 类继承于java.util.Date 类,为Date 类扩展了众多简便方法,这些方法多是DateUtil 静态方法的对象表现形式,使用DateTime 对象可以完全替代开发中Date 对象的使用。
package cn.hutool.core.date;
public class DateUtil extends CalendarUtil {
public static DateTime date(TemporalAccessor temporalAccessor) {
return new DateTime(temporalAccessor);
}
}
public class Test {
public static void main(String[] args) {
final LocalDateTime localDateTime = LocalDateTime.of(2022, 5, 9, 11, 36);
final Date date1 = Date.from(TemporalAccessorUtil.toInstant(localDateTime));
final DateTime date2 = DateUtil.date(localDateTime);
}
}
|