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

java时间戳转换

作者:昔日暖阳   发布日期:2025-06-15   浏览:58

// Java时间戳转换示例代码

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

public class TimestampConversion {

    public static void main(String[] args) {
        // 示例时间戳(毫秒)
        long timestamp = System.currentTimeMillis();

        // 将时间戳转换为LocalDateTime对象
        LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp)
                                             .atZone(ZoneId.systemDefault())
                                             .toLocalDateTime();

        // 格式化日期时间输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = localDateTime.format(formatter);

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

解释说明:

  1. 获取时间戳System.currentTimeMillis() 获取当前时间的时间戳,单位为毫秒。
  2. 转换为 LocalDateTime 对象:使用 Instant.ofEpochMilli() 方法将时间戳转换为 Instant 对象,再通过 atZone() 方法指定时区(这里使用系统默认时区),最后调用 toLocalDateTime() 转换为 LocalDateTime 对象。
  3. 格式化日期时间:使用 DateTimeFormatter 类定义日期时间的格式,并通过 format() 方法将 LocalDateTime 对象格式化为字符串。
  4. 输出结果:打印原始时间戳和格式化后的日期时间。

希望这段代码能帮助你理解如何在 Java 中进行时间戳的转换。

上一篇:java创建list并赋值

下一篇:java静态内部类

大家都在看

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 中文站