Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java 时间戳转日期

作者:尒忸旳迣鎅゛沬卜鋽旳凄涼   发布日期:2025-11-22   浏览:103

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class TimestampToDate {
    public static void main(String[] args) {
        // 示例时间戳(以秒为单位)
        long timestamp = 1633072800L;

        // 将时间戳转换为 Instant 对象
        Instant instant = Instant.ofEpochSecond(timestamp);

        // 指定时区,例如:中国标准时间 (CST)
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");

        // 将 Instant 转换为指定时区的日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(zoneId);
        String formattedDate = formatter.format(instant);

        // 输出结果
        System.out.println("转换后的日期时间为: " + formattedDate);
    }
}

解释说明:

  1. 时间戳long timestamp = 1633072800L; 是一个示例时间戳,表示自1970年1月1日00:00:00 UTC以来的秒数。
  2. InstantInstant.ofEpochSecond(timestamp) 将时间戳转换为 Instant 对象,表示时间线上的一个瞬间。
  3. 时区ZoneId.of("Asia/Shanghai") 指定了中国标准时间(CST)作为目标时区。
  4. 格式化DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(zoneId) 创建了一个日期时间格式化器,并指定了输出格式和时区。
  5. 输出System.out.println("转换后的日期时间为: " + formattedDate); 将格式化后的日期时间输出到控制台。

这段代码展示了如何将 Java 中的时间戳转换为可读的日期时间格式,并考虑了时区的影响。

上一篇:java获取文件大小

下一篇:java遍历数组

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站