import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class TimestampToDate {
public static void main(String[] args) {
// 假设我们有一个时间戳,例如:1633072800000 (毫秒)
long timestamp = 1633072800000L;
// 将时间戳转换为 Instant 对象
Instant instant = Instant.ofEpochMilli(timestamp);
// 设置时区,默认使用系统默认时区
ZoneId zoneId = ZoneId.systemDefault();
// 使用 DateTimeFormatter 格式化日期时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(zoneId);
// 将 Instant 对象格式化为指定的日期时间格式
String formattedDateTime = formatter.format(instant);
// 输出结果
System.out.println("转换后的日期时间: " + formattedDateTime);
}
}
时间戳:timestamp 是一个表示时间的长整型数值,单位是毫秒。这里假设的时间戳 1633072800000 对应的是 2021 年 10 月 1 日 12:00:00。
Instant:Instant.ofEpochMilli() 方法将时间戳转换为 Instant 对象,该对象表示时间线上的一个瞬时点。
时区:ZoneId.systemDefault() 获取系统的默认时区。你可以根据需要更改为其他时区,例如 ZoneId.of("UTC")。
格式化:DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") 定义了输出日期时间的格式。withZone(zoneId) 指定了时区。
格式化输出:formatter.format(instant) 将 Instant 对象格式化为指定的字符串格式并输出。
转换后的日期时间: 2021-10-01 12:00:00
上一篇:java连接mongodb数据库
下一篇:java防止接口重复请求
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站