Java8中的LocalDateTime和时间戳timestamp互相转换

将timestamp转为LocalDateTime

public LocalDateTime timestamToDatetime(long timestamp){
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

将LocalDataTime转为timestamp

public long datatimeToTimestamp(LocalDateTime ldt){
        long timestamp = ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        return timestamp;
    }

我在网上还找到了另一个将datetime转为时间戳的方法:
ZoneId zone = ZoneId.systemDefault();
long timestamp = ldt.atZone(zone).toInstant().toEpochMilli();

Java8的时间转为时间戳的大概的思路就是LocalDateTime先转为Instant,设置时区,然后转timestamp。

猜你喜欢

转载自blog.csdn.net/czx2018/article/details/85005466