简体   繁体   English

Windows和Unix之间的ZoneDateTime精度差异

[英]Difference in ZoneDateTime precision between Windows and Unix

I execute the following code and I got a different precision between Windows and Unix (macOs). 我执行以下代码,并且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()));
    }
}

Output on 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 ) is 在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

while on Windows 在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

Is there an expected output or a bug? 有预期的输出或错误吗?

I suspect you just happened to run at an instant where the time was on a 10ms boundary on the Mac. 我怀疑您恰好在Mac上的时间处于10毫秒边界的瞬间运行。

Here's some sample code to try: 这里是一些示例代码:

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);
            }
        }
    }
}

The output on my Windows box shows a mixture of output lengths. 我的Windows框上的输出显示输出长度的混合。 For example: 例如:

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

I suspect if you run that code in your various environments, you'll see the same result. 我怀疑如果您在各种环境中运行该代码,都会看到相同的结果。

If you need the same length for all output, I think you'll need to specify a custom pattern to DateTimeFormatter.ofPattern(String, Locale) . 如果所有输出都需要相同的长度,我想您需要为DateTimeFormatter.ofPattern(String, Locale)指定一个自定义模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM