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

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

作者:诸神之翼   发布日期:2026-04-28   浏览:37

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);
    }
}

解释说明:

  1. 时间戳timestamp 是一个表示时间的长整型数值,单位是毫秒。这里假设的时间戳 1633072800000 对应的是 2021 年 10 月 1 日 12:00:00。

  2. InstantInstant.ofEpochMilli() 方法将时间戳转换为 Instant 对象,该对象表示时间线上的一个瞬时点。

  3. 时区ZoneId.systemDefault() 获取系统的默认时区。你可以根据需要更改为其他时区,例如 ZoneId.of("UTC")

  4. 格式化DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") 定义了输出日期时间的格式。withZone(zoneId) 指定了时区。

  5. 格式化输出formatter.format(instant)Instant 对象格式化为指定的字符串格式并输出。

输出示例:

转换后的日期时间: 2021-10-01 12:00:00

上一篇:java连接mongodb数据库

下一篇:java防止接口重复请求

大家都在看

java url decode

java判断是windows还是linux

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java list 查找

java 解压rar

jsonobject.tojavaobje

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

Laravel 中文站