java.time.LocalDateTime与时间戳与Date相互转换
时间: 2023-12-12 16:59:41 浏览: 96
Java中实现LocalDateTime与Date相互转化
好的,这是一个技术问题,可以回答。可以使用以下代码实现相互转换:
1. LocalDateTime 转换为时间戳
```
LocalDateTime localDateTime = LocalDateTime.now();
long timestamp = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
```
2. 时间戳 转换为 LocalDateTime
```
long timestamp = System.currentTimeMillis();
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
```
3. Date 转换为 LocalDateTime
```
Date date = new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
```
4. LocalDateTime 转换为 Date
```
LocalDateTime localDateTime = LocalDateTime.now();
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
```
阅读全文