Java解析前端传来的Unix时间戳

在Java中,前端传递的 1749571200000 是一个 Unix时间戳(毫秒级) ,表示自1970年1月1日00:00:00 UTC以来经过的毫秒数。以下是两种常见的解析方式(推荐使用Java 8的java.time API):


方法1:使用 Java 8 的 java.time API(推荐)

java

复制

下载

复制代码
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class TimestampParser {
    public static void main(String[] args) {
        long timestamp = 1749571200000L; // 前端传来的时间戳
        
        // Step 1: 转换为 Instant (UTC时间)
        Instant instant = Instant.ofEpochMilli(timestamp);
        
        // Step 2: 转换为本地时间(根据系统时区)
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        
        // Step 3: 格式化输出(可选)
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = localDateTime.format(formatter);
        
        System.out.println("解析结果: " + formattedDate); // 输出: 2025-06-09 08:00:00
    }
}
关键点:
  • Instant.ofEpochMilli() 将毫秒时间戳转为 Instant(UTC标准时间)。

  • LocalDateTime.ofInstant() 结合时区(如 ZoneId.systemDefault())转换为本地时间。

  • 使用 DateTimeFormatter 自定义日期格式。


方法2:使用旧版 java.util.Date(兼容旧项目)

java

复制

下载

复制代码
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class LegacyTimestampParser {
    public static void main(String[] args) {
        long timestamp = 1749571200000L; // 前端传来的时间戳
        
        // Step 1: 创建Date对象
        Date date = new Date(timestamp);
        
        // Step 2: 设置日期格式化器(指定时区)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 按需修改时区
        
        // Step 3: 格式化输出
        String formattedDate = sdf.format(date);
        
        System.out.println("解析结果: " + formattedDate); // 输出: 2025-06-09 08:00:00
    }
}

时区说明

  • 前端时间戳 通常是UTC时间,解析时需要明确目标时区:

    • 如果前端传递的是UTC时间,解析时建议先转UTC再按需调整时区。

    • 示例中 Asia/Shanghai(UTC+8)会导致时间+8小时。

  • 关键时区设置:

    • Java 8: ZoneId.of("UTC")ZoneId.systemDefault()

    • 旧版API: sdf.setTimeZone(TimeZone.getTimeZone("UTC"))


验证时间戳

  • 工具验证:https://www.epochconverter.com/

  • 1749571200000 对应 UTC时间 2025-06-09 00:00:00

    转换为北京时间(UTC+8)则是 2025-06-09 08:00:00


总结

场景 方案
Java 8+ 项目 优先使用 Instant + LocalDateTime
兼容旧系统 (Java 7-) 使用 Date + SimpleDateFormat
时区敏感 务必显式设置目标时区
相关推荐
小鹏linux34 分钟前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
RyFit1 小时前
SpringAI 常见问题及解决方案大全
java·ai
石山代码1 小时前
C++ 内存分区 堆区
java·开发语言·c++
前端若水1 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
绝知此事2 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
Bigger2 小时前
mini-cc:一个轻量级 AI 编程助手的诞生
前端·ai编程·claude
无风听海2 小时前
C# 隐式转换深度解析
java·开发语言·c#
涵涵(互关)2 小时前
Naive-ui树型选择器只显示根节点
前端·ui·vue
BY组态2 小时前
Ricon组态系统最佳实践:从零开始构建物联网监控平台
前端·物联网·iot·web组态·组态
BY组态2 小时前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·物联网·iot·web组态·组态