You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SimpleDateFormat转换时间戳1629777600000不生效该如何解决?

问题原因
  • 变量名拼写不一致:代码中定义的SimpleDateFormat实例变量名为simpleDateFormatter,调用format方法时使用的是simpleDateFormat,名称不匹配会直接导致编译报错,无法正常运行。
  • 数值类型不匹配:1629777600000已经超出int类型的最大值范围,如果你没有给数值加L后缀标识为long类型,编译器会默认判定为int类型,触发数值溢出报错。
  • 时区不匹配:如果上述问题都修正后还是得到不符合预期的日期,是因为SimpleDateFormat默认使用当前运行环境的系统时区,而数据库存储的时间戳一般为UTC时区的毫秒值,时区偏差会导致格式化结果和预期不符。
修复方案

基础修复(兼容Java所有版本)

修正变量名、添加long类型标识,同时明确指定和数据库一致的时区即可:

import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class DateTest {
    public static void main(String[] args) {
        SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("MM/dd/yyyy");
        // 明确指定时区为UTC,和数据库存储的时间戳时区保持一致
        simpleDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        // 时间戳后加L标识为long类型,避免溢出
        String formatResult = simpleDateFormatter.format(1629777600000L);
        // 输出结果为 08/24/2021
        System.out.println(formatResult);
    }
}

优化方案(Java 8及以上推荐)

SimpleDateFormat是非线程安全的,多线程环境下使用容易出现异常,推荐用java.time包下的线程安全类替代:

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

public class DateTest {
    public static void main(String[] args) {
        Instant timestamp = Instant.ofEpochMilli(1629777600000L);
        ZonedDateTime utcTime = timestamp.atZone(ZoneId.of("UTC"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        String formatResult = utcTime.format(formatter);
        // 输出结果为 08/24/2021
        System.out.println(formatResult);
    }
}

内容的提问来源于stack exchange,提问作者halfpenny-ian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:15:03