如何在 Java.time 中将 LocalDateTime 的精度设置为纳秒?
How to set precision of LocalDateTime to nanoseconds in Java.time?
根据 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 可用的分辨率高于毫秒的时钟。
Update - 您还可以使用 LocalDateTime.of()
创建一个 LocalDateTime
来验证纳秒是否已存储并将包含在 return 中默认 LocalDateTime.toString()
方法的值:
LocalDateTime when =
LocalDateTime.of(2016, Month.AUGUST, 12, 9, 38, 12, 123456789);
System.out.println(when);
上面的输出将是:
2016-08-12T09:38:12.123456789
使用LocaleDateTime.now().getNano()
你只是在做 System.out.println(LocalDateTime.now())
。这使用 toString()
方法,如果它们为零则不显示纳秒。
根据 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 可用的分辨率高于毫秒的时钟。
Update - 您还可以使用 LocalDateTime.of()
创建一个 LocalDateTime
来验证纳秒是否已存储并将包含在 return 中默认 LocalDateTime.toString()
方法的值:
LocalDateTime when =
LocalDateTime.of(2016, Month.AUGUST, 12, 9, 38, 12, 123456789);
System.out.println(when);
上面的输出将是:
2016-08-12T09:38:12.123456789
使用LocaleDateTime.now().getNano()
你只是在做 System.out.println(LocalDateTime.now())
。这使用 toString()
方法,如果它们为零则不显示纳秒。