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

前端 未结 1 1518
猫巷女王i
猫巷女王i 2021-02-19 07:54

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.

1条回答
  •  青春惊慌失措
    2021-02-19 08:25

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

    0 讨论(0)
提交回复
热议问题