如何在 Java.time 中将 LocalDateTime 的精度设置为纳秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38905887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set precision of LocalDateTime to nanoseconds in Java.time?
提问by Steven Hu
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.
根据java.time 文档,java.time 应该能够以纳秒精度呈现 LocalDateTime 或 LocalTime,但是当我运行LocalDateTime.now()
并打印出来时,它只显示 3 位而不是 9 位。
Like this:
像这样:
2016-08-11T22:17:35.031
Is there a way to get a higher precision?
有没有办法获得更高的精度?
回答by Sean Bright
I am assuming you are just using LocalDateTime.toString()
, in which case the documentationreads:
我假设您只是在使用LocalDateTime.toString()
,在这种情况下,文档内容如下:
The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.
所使用的格式将是输出完整时间值的最短格式,其中省略部分暗示为零。
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
并使用它:
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS");
System.out.println(LocalDateTime.now().format(formatter));
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.now()
使用Clock
仅保证具有毫秒精度的系统默认值,但如果可用,可以使用更高分辨率的时钟。您的平台可能没有可供 JRE 使用且分辨率高于毫秒的时钟。
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
withLocalDateTime.of()
来验证是否存储了纳秒并将其包含在默认LocalDateTime.toString()
方法的返回值中:
LocalDateTime when =
LocalDateTime.of(2016, Month.AUGUST, 12, 9, 38, 12, 123456789);
System.out.println(when);
The output of the above would be:
上面的输出将是:
2016-08-12T09:38:12.123456789
回答by Bilal BBB
Use LocaleDateTime.now().getNano()
利用 LocaleDateTime.now().getNano()
You are just doing System.out.println(LocalDateTime.now())
. This uses toString()
method which doesn't show nanoseconds if they are zero.
你只是在做System.out.println(LocalDateTime.now())
。toString()
如果它们为零,则使用不显示纳秒的方法。