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
时区敏感 务必显式设置目标时区
相关推荐
再学一点就睡7 小时前
前端网络实战手册:15个高频工作场景全解析
前端·网络协议
num_killer7 小时前
小白的Langchain学习
java·python·学习·langchain
C_心欲无痕8 小时前
有限状态机在前端中的应用
前端·状态模式
C_心欲无痕8 小时前
前端基于 IntersectionObserver 更流畅的懒加载实现
前端
candyTong8 小时前
深入解析:AI 智能体(Agent)是如何解决问题的?
前端·agent·ai编程
期待のcode8 小时前
Java虚拟机的运行模式
java·开发语言·jvm
程序员老徐8 小时前
Tomcat源码分析三(Tomcat请求源码分析)
java·tomcat
柳杉8 小时前
建议收藏 | 2026年AI工具封神榜:从Sora到混元3D,生产力彻底爆发
前端·人工智能·后端
weixin_462446238 小时前
使用 Puppeteer 设置 Cookies 并实现自动化分页操作:前端实战教程
运维·前端·自动化
a程序小傲8 小时前
京东Java面试被问:动态规划的状态压缩和优化技巧
java·开发语言·mysql·算法·adb·postgresql·深度优先