根据java.time documentation ,java.time 应该能够以纳秒精度呈现 LocalDateTime 或 LocalTime,但是当我运行 LocalDateTime.now()
并打印出来时,它只显示 3 位数字而不是 9。
像这样:
2016-08-11T22:17:35.031
有没有办法获得更高的精度?
最佳答案
我假设您只是使用 LocalDateTime.toString()
,在这种情况下 the documentation 读取:
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
并使用它:
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS");
System.out.println(LocalDateTime.now().format(formatter));
此外,LocalDateTime.now()
使用系统默认的 Clock
,它仅保证具有毫秒精度,但可以使用更高分辨率的时钟(如果可用)。您的平台可能没有可用于 JRE 且分辨率高于毫秒的时钟。
更新 - 您还可以使用 LocalDateTime.of()
创建一个 LocalDateTime
来验证纳秒是否已存储并将包含在默认 LocalDateTime.toString()
方法的返回值:
LocalDateTime when =
LocalDateTime.of(2016, Month.AUGUST, 12, 9, 38, 12, 123456789);
System.out.println(when);
上面的输出将是:
2016-08-12T09:38:12.123456789
关于java - 如何在Java.time中将LocalDateTime的精度设置为纳秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905887/