Java 时间戳转Date
在Java中,可以使用java.util.Date类将时间戳转换为日期对象。下面是一个示例代码:
import java.util.Date;
public class TimestampToDate {
public static void main(String[] args) {
// 以毫秒为单位的时间戳
long timestamp = 1634650400000L;
// 将时间戳转换为Date对象
Date date = new Date(timestamp);
// 输出日期对象
System.out.println(date);
}
}
在上面的示例中,我们使用Date类的构造函数将时间戳转换为日期对象。构造函数接受以毫秒为单位的时间戳作为参数。
运行以上代码将输出日期对象的字符串表示,例如Sat Oct 23 00:00:00 CST 2021。
请注意,java.util.Date类在Java 8中已被废弃,推荐使用java.time.Instant类来处理时间戳。以下是使用Instant类将时间戳转换为日期对象的示例代码:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class TimestampToDate {
public static void main(String[] args) {
// 以秒为单位的时间戳
long timestamp = 1634650400L;
// 将时间戳转换为Instant对象
Instant instant = Instant.ofEpochSecond(timestamp);
// 将Instant对象转换为本地日期时间对象
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// 将本地日期时间对象转换为带时区的日期时间对象
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
// 输出日期时间对象
System.out.println(zonedDateTime);
}
}
在上面的示例中,我们使用Instant类的ofEpochSecond方法将以秒为单位的时间戳转换为Instant对象。然后,我们使用LocalDateTime类和ZonedDateTime类将Instant对象转换为带时区的日期时间对象。最后,我们输出日期时间对象的字符串表示,例如2021-10-19T00:00+08:00[Asia/Shanghai]
原文地址: https://www.cveoy.top/t/topic/igs3 著作权归作者所有。请勿转载和采集!