LocalDateTime转换为UTC时间戳
时间: 2023-10-14 13:19:08 浏览: 104
本地时间转为UTC时间
4星 · 用户满意度95%
可以使用Java 8提供的java.time包中的类来实现LocalDateTime到UTC时间戳的转换。具体步骤如下:
1. 首先需要获取当前的UTC时间戳,可以使用Instant类的now()方法来获取:
```
Instant instant = Instant.now();
```
2. 将LocalDateTime转换为Instant,可以使用atZone()方法指定时区创建一个ZonedDateTime对象,然后再通过toInstant()方法获取Instant对象:
```
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
```
3. 将Instant对象转换为UTC时间戳,可以使用toEpochMilli()方法获取从1970年1月1日00:00:00开始的毫秒数:
```
long timestamp = instant.toEpochMilli();
```
完整代码示例如下:
```
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class LocalDateTimeToTimestamp {
public static void main(String[] args) {
// 获取当前UTC时间戳
Instant instant = Instant.now();
long timestamp1 = instant.toEpochMilli();
System.out.println("Current UTC timestamp: " + timestamp1);
// 将LocalDateTime转换为UTC时间戳
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
Instant instant2 = zonedDateTime.toInstant();
long timestamp2 = instant2.toEpochMilli();
System.out.println("LocalDateTime to UTC timestamp: " + timestamp2);
}
}
```
输出结果:
```
Current UTC timestamp: 1626868411834
LocalDateTime to UTC timestamp: 1626868411834
```
阅读全文