Windows和Unix之间ZoneDateTime精度的差异

时间:2018-01-31 10:06:37

标签: java windows unix jvm

我执行以下代码,我在Windows和Unix(macOs)之间获得了不同的精度。

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

public class TimeTest {

    public static void main(String[] args) {
        System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()));
    }
}

MacOS上的输出(Darwin Nicolass-MacBook-Pro.local 17.3.0 Darwin Kernel Version 17.3.0: Thu Nov 9 18:09:22 PST 2017; root:xnu-4570.31.3~1/RELEASE_X86_64 x86_64)是

> java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
> java TimeTest 
2018-01-31T11:05:49.59+01:00
在Windows上

>java -version
java version "1.8.0_161"
Java(TM) SE Runtime Environment (build 1.8.0_161-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mode)

>java TimeTest
2018-01-31T11:02:22.452+01:00

是否有预期的输出或错误?

1 个答案:

答案 0 :(得分:2)

我怀疑你刚刚碰巧在Mac上10ms边界的时间运行。

以下是一些示例代码:

import java.time.*;
import java.time.format.*;

class Test {
    public static void main(String[] args) throws Exception {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

        String last = "";
        while (true) {
            String next = formatter.format(ZonedDateTime.now());
            if (!last.equals(next)) {
                last = next;
                System.out.println(next);
            }
        }
    }
}

我的Windows框中的输出显示了输出长度的混合。例如:

2018-01-31T10:17:34.589Z
2018-01-31T10:17:34.59Z
2018-01-31T10:17:34.591Z
2018-01-31T10:17:34.592Z
2018-01-31T10:17:34.593Z
2018-01-31T10:17:34.594Z
2018-01-31T10:17:34.595Z
2018-01-31T10:17:34.596Z
2018-01-31T10:17:34.597Z
2018-01-31T10:17:34.598Z
2018-01-31T10:17:34.599Z
2018-01-31T10:17:34.6Z
2018-01-31T10:17:34.601Z

我怀疑如果你在各种环境中运行该代码,你会看到相同的结果。

如果所有输出需要相同的长度,我认为您需要为DateTimeFormatter.ofPattern(String, Locale)指定自定义模式。