如何在Java.time中将LocalDateTime的精度设置为纳秒? [英] How to set precision of LocalDateTime to nanoseconds in Java.time?

查看:3902
本文介绍了如何在Java.time中将LocalDateTime的精度设置为纳秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 java.time文档,java.time应该能够以纳秒精度呈现LocalDateTime或LocalTime,但是当我运行 LocalDateTime.now()并打印出来时,它只显示3数字而不是9。

According to the java.time documentation, java.time should be able to present a LocalDateTime or LocalTime with nanoseconds precision, but when I run LocalDateTime.now() and print out, it only shows 3 digits instead of 9.

喜欢这样:

2016-08-11T22:17:35.031

有没有办法获得更高的精度?

Is there a way to get a higher precision?

推荐答案

我假设您只是使用 LocalDateTime.toString(),在这种情况下< a href =https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#toString--\"rel =nofollow>文档上写着:

I am assuming you are just using LocalDateTime.toString(), in which case the documentation reads:


使用的格式是最短的,输出省略的部分隐含为零的时间的全部值。

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

如果你想要额外的数字要显示,即使它们是零,您还需要创建一个 DateTimeFormatter 并改为使用:

If you want additional digits to show up, even if they are zeroes, you will need to create a DateTimeFormatter and use that instead:

DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS");

System.out.println(LocalDateTime.now().format(formatter));

此外, LocalDateTime.now()使用系统默认 时钟 仅保证具有毫秒精度,但如果可用,则可以使用更高分辨率的时钟。您的平台可能没有可用于JRE的时钟,其分辨率高于毫秒。

Further, LocalDateTime.now() uses the system default Clock which is only guaranteed to have millisecond precision, but can use a higher resolution clock if one is available. It's possible that your platform doesn't have a clock that is available to the JRE with a higher resolution than milliseconds.

更新 - 您可以还可以使用 LocalDateTime.of()创建 LocalDateTime ,以验证是否存储纳秒并将包含在返回值中默认 LocalDateTime.toString()方法:

Update - You can also create a LocalDateTime with LocalDateTime.of() to verify that nanoseconds are stored and will be included in the return value of the default LocalDateTime.toString() method:

LocalDateTime when =
    LocalDateTime.of(2016, Month.AUGUST, 12, 9, 38, 12, 123456789);

System.out.println(when);

上述输出为:


2016-08-12T09:38:12.123456789

这篇关于如何在Java.time中将LocalDateTime的精度设置为纳秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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