找到你要的答案

Q:java.time ISO date format with fixed millis digits (in Java 8 and later)

Q:java.time ISO日期格式固定信息位数(java 8以后的版本)

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?

默认情况下,toString方法即时使用datetimeformatter.iso_instant格式化程序。,格式化不会打印数字部分的第二如果他们碰巧是0。

java的例子:

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

Joda-Time的例子(和我期望从java的时候。):

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

这是令人沮丧的解析在一些系统。Elasticsearch是我遇到的第一个问题,没有预先定义的格式,支持可选的信息,但是我可以工作在一个自定义格式。默认似乎只是错误的。

看来你真的不能建立自己的时间格式字符串无论如何。是唯一的选择,实现自己的java.time.format.datetimeformatterbuilder.instantprinterparser?

answer1: 回答1:

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. …

只是创建一个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是用于输出多位数必须避免任何尾随零。…

java  java-8  jodatime  java-time