具有固定毫位数的java.time ISO日期格式(在Java 8及更高版本中)
默认情况下, Instant
的toString
方法使用DateTimeFormatter.ISO_INSTANT格式化程序。 如果格式化程序碰巧为0,则不会打印秒数的数字。
java时间示例:
2015-10-08T17:13:07.589Z 2015-10-08T17:13:07Z
Joda-Time示例(以及我对java.time的期望):
2015-10-08T17:13:07.589Z 2015-10-08T17:13:07.000Z
在一些系统中解析这真的很令人沮丧。 Elasticsearch是我遇到的第一个问题,没有预定义的格式支持可选的millis,但我可以用自定义格式解决这个问题。 默认似乎是错误的。
看来你无法为Instants构建自己的格式字符串。 是实现我自己的java.time.format.DateTimeFormatterBuilder.InstantPrinterParser的唯一选项吗?
只需创建一个保留三个小数位的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
类doc的摘录:
… fractionalDigits参数允许控制小数秒的输出。 指定零将导致不输出小数位。 从1到9将输出越来越多的数字,必要时使用零右边填充。 特殊值-1用于输出必要的数字以避免任何尾随零。 …