Java 13位时间戳转换为日期格式 - 代码示例与解析
在Java中,可以使用java.time包中的Instant类来将13位时间戳转换为日期格式。下面是一个示例代码:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class TimestampToDateConverter {
public static void main(String[] args) {
long timestamp = 1569436200000L; // 13位时间戳
// 将时间戳转换为Instant对象
Instant instant = Instant.ofEpochMilli(timestamp);
// 将Instant对象转换为LocalDateTime对象
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss');
// 格式化日期
String formattedDateTime = dateTime.format(formatter);
// 输出结果
System.out.println(formattedDateTime);
}
}
在上面的示例中,我们首先将13位时间戳转换为Instant对象,然后使用LocalDateTime.ofInstant()方法将其转换为LocalDateTime对象。接下来,我们定义了日期格式yyyy-MM-dd HH:mm:ss,并使用DateTimeFormatter对日期进行格式化。最后,我们打印出格式化后的日期。
原文地址: https://www.cveoy.top/t/topic/o8Bs 著作权归作者所有。请勿转载和采集!