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

使用JodaTime从Long值创建DateTime出现时间偏差问题求助

问题原因与解决方案

这个问题我之前踩过坑,核心原因是时区设置在作祟!

为什么会输出01:00:00,005?

JodaTime的DateTime(long instant)构造器默认会采用当前JVM的默认时区来生成日期时间对象。你传入的5代表的是从**UTC纪元起点(1970-01-01T00:00:00.000Z)**开始的5毫秒,也就是UTC标准时间的00:00:00,005。

但如果你的JVM默认时区是UTC+1(比如欧洲中部时间、西非时间等),本地时间会比UTC时间快1小时,所以最终格式化后的结果就变成了01:00:00,005。

怎么得到预期的00:00:00,005?

有三种常用的解决方式,核心都是强制使用UTC时区来处理:

  1. 创建DateTime时直接指定UTC时区

    DateTime e = new DateTime(new Long("5"), DateTimeZone.UTC);
    System.out.println(e.toString(DateTimeFormat.forPattern("HH:mm:ss,SSS")));
    
  2. 格式化时指定UTC时区

    DateTime e = new DateTime(new Long("5"));
    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss,SSS").withZone(DateTimeZone.UTC);
    System.out.println(formatter.print(e));
    
  3. 将已有的DateTime对象转换为UTC时区

    DateTime e = new DateTime(new Long("5")).withZone(DateTimeZone.UTC);
    System.out.println(e.toString(DateTimeFormat.forPattern("HH:mm:ss,SSS")));
    

额外提示

你原来用的hh是12小时制的小时格式,UTC纪元起点的0点用hh会输出12(对应12小时制的凌晨)。如果想要24小时制的00,记得把格式符改成HH,这样输出会完全符合你的预期。

内容的提问来源于stack exchange,提问作者chris000r

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:30:21