秒级字符串时间戳转LocalDateTime 北京时间
时间: 2023-07-20 14:19:55 浏览: 61
如果你需要将秒级字符串时间戳转换为北京时间的LocalDateTime,你可以使用ZoneId.of("Asia/Shanghai")方法来指定时区。以下是一个示例代码:
```
String timestamp = "1620082800";
long epochSeconds = Long.parseLong(timestamp);
LocalDateTime datetime = LocalDateTime.ofEpochSecond(epochSeconds, 0, ZoneOffset.UTC);
LocalDateTime beijingTime = datetime.atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
```
在这个示例中,我们首先使用UTC时区将时间戳转换为LocalDateTime对象,然后使用atZone()方法将其转换为指定时区的ZonedDateTime对象,最后使用toLocalDateTime()方法将其转换为北京时间的LocalDateTime对象。
相关问题
秒级字符串时间戳转LocalDateTime
你可以使用Java 8中的DateTimeFormatter类将字符串时间戳转换为LocalDateTime。以下是一个示例代码:
```
String timestamp = "1620082800";
long epochSeconds = Long.parseLong(timestamp);
LocalDateTime datetime = LocalDateTime.ofEpochSecond(epochSeconds, 0, ZoneOffset.UTC);
```
这里,我们首先将时间戳字符串转换为long类型的epoch seconds,然后使用LocalDateTime.ofEpochSecond()方法将其转换为LocalDateTime对象。在这个示例中,我们使用UTC时区,你可以根据需要更改时区。
时间戳转LocalDateTime
以下是将时间戳转换为LocalDateTime的Python代码示例:
```python
import datetime
# 将时间戳转换为LocalDateTime
timestamp = 1626844800 # 时间戳,单位为秒
dt_object = datetime.datetime.fromtimestamp(timestamp)
# 输出转换后的LocalDateTime
print("LocalDateTime:", dt_object)
```
在上面的代码中,我们使用了Python内置的datetime模块来将时间戳转换为LocalDateTime。具体来说,我们使用了`fromtimestamp()`函数将时间戳转换为LocalDateTime对象,并将其存储在`dt_object`变量中。最后,我们使用`print()`函数输出转换后的LocalDateTime。