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

Ed *_*mas 13 java jodatime java-8 java-time

默认情况下,使用DateTimeFormatter.ISO_INSTANT格式化程序的toString方法.如果格式化程序碰巧为0,则不会打印秒数的数字.Instant

java时间示例:

    2015-10-08T17:13:07.589Z
    2015-10-08T17:13:07Z
Run Code Online (Sandbox Code Playgroud)

Joda-Time示例(以及我对java.time的期望):

    2015-10-08T17:13:07.589Z
    2015-10-08T17:13:07.000Z
Run Code Online (Sandbox Code Playgroud)

在一些系统中解析这真的很令人沮丧.Elasticsearch是我遇到的第一个问题,没有预定义的格式支持可选的millis,但我可以使用自定义格式解决这个问题.默认似乎是错误的.

看来你无法为Instants构建自己的格式字符串.是实现我自己的java.time.format.DateTimeFormatterBuilder.InstantPrinterParser的唯一选择吗?

Sot*_*lis 14

只需创建一个DateTimeFormatter保留三个小数位的数字.

DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendInstant(3).toFormatter();
Run Code Online (Sandbox Code Playgroud)

然后使用它.例如:

System.out.println(formatter.format(Instant.now()));
System.out.println(formatter.format(Instant.now().truncatedTo(ChronoUnit.SECONDS)));
Run Code Online (Sandbox Code Playgroud)

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

2015-10-08T21:26:16.571Z
2015-10-08T21:26:16.000Z
Run Code Online (Sandbox Code Playgroud)

类doc的摘录:

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