为什么通过 SimpleDateFormat 解析时 Java 纪元时间会减少 30 分钟

问题描述 投票:0回答:1

不知何故,解析日期时间字符串并将其转换为纪元后的毫秒数在不同环境中的工作方式有所不同。时区之类的东西似乎有问题。理论上,这个字符串应该代表纪元以来的 0 秒:“1970-01-01T00:00:00Z”

实际上,在开发人员机器上,它神秘地是 30 分钟(18000000 毫秒)。

    /**
     * This really ought to return 0, but locally it returns 30 minutes worth of milliseconds.
     * @return The milliseconds since the common epoch. Really ought to be zero, but isn't always.
     */
    public long determineMysteriousMachineTimeDelta()  {
        String strDateOfEpochStart = "1970-01-01T00:00:00Z";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date dateStartOfEpoch = null;
        try {
            dateStartOfEpoch = format.parse(strDateOfEpochStart);

        } catch (ParseException e) {
            return -1;
        }
        return dateStartOfEpoch.getTime();
    }

谢谢!

java simpledateformat epoch
1个回答
0
投票

Z
,从来没有
'Z'

切勿在格式模式中的

Z
周围添加引号。

该字母表示与 UTC 的偏移量为零时-分-秒。发音为“祖鲁”。

您的引号表示“期待此文本,但忽略它”。所以你的格式化模式会丢弃关键信息。

避免遗留日期时间类

切勿使用

SimpleDateFormat
Calendar
Date
类。这些都是遗留类,并且存在严重缺陷。它们几年前就被 JSR 310 中定义的现代 java.time 类所取代。

java.time

© www.soinside.com 2019 - 2024. All rights reserved.