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

java时间戳转换成年月日时分秒

作者:烟寂断魂   发布日期:2025-07-04   浏览:82

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

public class TimestampConverter {
    public static String convertTimestampToDateTime(long timestamp) {
        // 创建 Instant 对象,表示时间戳(以秒为单位)
        Instant instant = Instant.ofEpochSecond(timestamp);

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

        // 格式化输出
        return formatter.format(instant);
    }

    public static void main(String[] args) {
        // 示例时间戳(秒)
        long timestamp = 1633072800L;
        System.out.println(convertTimestampToDateTime(timestamp));
    }
}

解释说明:

  1. InstantInstant 类表示时间线上的一个瞬时点,通常用于表示 UTC 时间。我们使用 Instant.ofEpochSecond() 方法将时间戳(以秒为单位)转换为 Instant 对象。
  2. ZoneIdZoneId.systemDefault() 获取系统的默认时区。你可以根据需要更改为其他时区,例如 ZoneId.of("Asia/Shanghai")
  3. DateTimeFormatterDateTimeFormatter 用于定义日期和时间的格式。这里我们定义了 yyyy-MM-dd HH:mm:ss 的格式。
  4. convertTimestampToDateTime 方法:该方法接收一个时间戳(以秒为单位),并返回格式化后的日期时间字符串。
  5. main 方法:示例代码中使用了一个时间戳 1633072800L,并调用 convertTimestampToDateTime 方法将其转换为年月日时分秒格式并打印出来。

如果你运行这段代码,它会输出类似如下的结果(具体取决于你的时间戳和时区):

2021-10-01 12:00:00

上一篇:protobuf java

下一篇:java获取请求的ip地址

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

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

Laravel 中文站