且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有固定毫位数的java.time ISO日期格式(在Java 8及更高版本中)

更新时间:2023-01-17 08:08:32

只需创建一个 DateTimeFormatter 保留三个小数位。

  DateTimeFormatter formatter = new DateTimeFormatterBuilder()。appendInstant(3).toFormatter(); 

然后使用它。例如:

  System.out.println(formatter.format(Instant.now())); 
System.out.println(formatter.format(Instant.now()。truncatedTo(ChronoUnit.SECONDS)));

...打印(当我运行时):

  2015-10-08T21:26:16.571Z 
2015-10-08T21:26:16.000Z

类文档


... fractionalDigits参数允许输出要控制的小数秒。指定零将导致不输出小数位。从1到9将输出越来越多的数字,必要时使用零右边填充。特殊值-1用于输出必要的数字以避免任何尾随零。 ...



By default, the toString method of Instant uses the DateTimeFormatter.ISO_INSTANT formatter. That formatter won’t print the digits for fraction-of-second if they happen to be 0.

java-time examples:

    2015-10-08T17:13:07.589Z
    2015-10-08T17:13:07Z

Joda-Time examples (and what I'd expect from java.time):

    2015-10-08T17:13:07.589Z
    2015-10-08T17:13:07.000Z

This is really frustrating to parse in some systems. Elasticsearch was the first problem I encountered, there's no pre-defined format that supports optional millis, but I can probably work around that with a custom format. The default just seems wrong.

It appears that you can’t really build your own format string for Instants anyway. Is the only option implementing my own java.time.format.DateTimeFormatterBuilder.InstantPrinterParser?

Just create a DateTimeFormatter that keeps three fractional digits.

DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendInstant(3).toFormatter();

Then use it. For example:

System.out.println(formatter.format(Instant.now()));
System.out.println(formatter.format(Instant.now().truncatedTo(ChronoUnit.SECONDS)));

…prints (at the time I run it):

2015-10-08T21:26:16.571Z
2015-10-08T21:26:16.000Z

Excerpt of the class doc:

… The fractionalDigits parameter allows the output of the fractional second to be controlled. Specifying zero will cause no fractional digits to be output. From 1 to 9 will output an increasing number of digits, using zero right-padding if necessary. The special value -1 is used to output as many digits as necessary to avoid any trailing zeroes. …