彻底搞清楚 Java 中LocalDateTime util.Date 以及毫秒数之间的关系

361 阅读1分钟

对比组1

1.LocalDateTime ->毫秒数

LocalDateTime start=LocalDateTime.of(2023,2,2,0,0,0);
ZonedDateTime zonedDateTime = start.atZone(ZoneId.of("Asia/Shanghai"));
Instant instant = Instant.from(zonedDateTime);
long milli= instant.toEpochMilli();

2.LocalDateTime->java.util.Date

LocalDateTime start=LocalDateTime.of(2023,2,2,0,0,0);
ZonedDateTime zonedDateTime = start.atZone(ZoneId.of("Asia/Shanghai"));
Instant instant = Instant.from(zonedDateTime);
Date date=Date.from(instant);  //底层代码 new Date(instant.toEpochMilli())

3.对比结果发现

当从LocalDateTime 转换成Instant 以后,

Instant 对象直接toEpochMill() 就可以获取到对应时间的毫秒数

如果要转成Date 类型,直接通过new Date(long mills) 来获得

所以LocalDateTime 转 毫秒和Util.Date 的关键是 转成 Instant

LocalDateTime 转成 Instant 的关键是:构建ZonedDateTime 对象

Instant.from(ZonedDateTime zonedDateTime) :从指定的时间获取一个瞬间

对比组2

1.Date 转LocalDateTime

Date currentDate =new Date();
Instant instant = currentDate.toInstant();// Date的这个toInstant()方法底层是 
                                        // Instant.OfEpochMilli(getTime())
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

2.毫秒转LocalDateTime

Long ntTime=1675296000000l;
Instant instant=Instant.ofEpochMilli(ntTime);
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime=instant.atZone(zoneId).toLocalDateTime();

3.对比结果

从Date 或者 毫秒转LocalDateTime 的关键也是构建Instant对象-》这个瞬间对象

Date.toInstant() Instant.ofEpochMill(ntTime) 分别从Date 和long 构建完Instant 对象,

其中Date.toInstant() 底层也是使用Instant.ofEpochMilli(date.getTime()) 来构建Instant 对象

Instant对象设置了Zone信息以后,可以通过 ZonedDateTime.toLocalDateTime()

得到LocalDateTime

 

附加:从操作系统的纳秒转成LocalDateTime

public static final long TICKS_AT_EPOCH_NT=116444736000000000L;
public static final long TICKS_AT_PER_MILLISECOND=10000L;
public static TimeZone TIME_ZONE=TimeZone.getDefault();

public static LocalDateTime changeNTToLocalDateTime2(Long ntTime) {
    if(Optional.ofNullable(ntTime).isPresent()){
        Calendar calendar = Calendar.getInstance(TIME_ZONE);
        calendar.setTimeInMillis((ntTime-TICKS_AT_EPOCH_NT)/TICKS_AT_PER_MILLISECOND);
        Instant instant = calendar.getTime().toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }else{
        return null;
    }
}