Java 8和Java 9之间的ZoneDateTime精度差异 [英] Difference in ZoneDateTime precision between Java 8 and Java 9

查看:119
本文介绍了Java 8和Java 9之间的ZoneDateTime精度差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下代码,我在Java 8和Java 9之间获得了不同的精度.

I execute the following code and I got a different precision between Java 8 and Java 9.

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

使用Java 8输出

$ 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-31T10:30:49.397Z

在使用Java 9时

$ java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)
$ java TimeTest
2018-01-31T10:30:02.343193Z

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

Is there an expected output or a bug?

推荐答案

javadoc(至少是Java 8的javadoc)指出:

The javadoc (at least that of java 8) states:

1到9位数的纳秒.尽可能多的数字 输出.

One to nine digits for the nano-of-second. As many digits will be output as required.

所以两者都是正确的.

此外,ISO-8601状态的规范(来自维基百科):

Furthermore the specification of ISO-8601 states (from Wikipedia):

小数部分的小数位数没有限制.

There is no limit on the number of decimal places for the decimal fraction.

更具体地说,我深入调试Java库代码.

To be more specific, I dove into debugging Java library code.

小数秒的内部表示形式是397000000,然后将其划分并最终馈入BigDecimal.stripTrailingZeros()以获得.397.

The internal representation of the fractional seconds is 397000000 which is then divided and eventually fed into BigDecimal.stripTrailingZeros() to obtain .397.

Java 9返回更多数字的原因是,除了Java和Java都使用System.currentTimeMillis()之外,Java 9还调用了VM.getNanoTimeAdjustment().

The reason why Java 9 returns more digits is because in addition to using System.currentTimeMillis() which both Java do, Java 9 also calls VM.getNanoTimeAdjustment().

这篇关于Java 8和Java 9之间的ZoneDateTime精度差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆