79566304

Date: 2025-04-10 09:53:55
Score: 1
Natty:
Report link

DateTimeFormatterBuilder.appendInstant(int fractionalDigits)

As a supplement to the answer by Basil Bourque, if you prefer, you can create a formatter that leaves out the fractional seconds of an Instant. You will still have to delete T and Z yourself if you don’t want them. So you may consider that it is not worth it.

The formatter would be:

public static final DateTimeFormatter instantFormatterNoSeconds
        = new DateTimeFormatterBuilder()
                .appendInstant(0)
                .toFormatter(Locale.ROOT);

The 0 passed to appendInstant() specifies that we want no fractional digits.

Demonstration:

    String noFractionalSeconds = instantFormatterNoSeconds.format(Instant.MAX);
    String noTAndZ = noFractionalSeconds.replace('T', ' ').replace("Z", "");
    System.out.println(noTAndZ);

Output:

+1000000000-12-31 23:59:59

Why did your code fail?

It seems to be a design decision that the formatters obtained from DateTimeFormatter.ofPattern() do not support the last some 400 days of the range supported by Instant. It may have to do with not wanting to risk that parsing with such a formatter would lead to values that are out of range for other date-time types such as LocalDateTime; but this is speculation.

Basil Bourque in his answer correctly mentions that year 1 000 000 000 does not fit with your specification of a 4 digit year. This has nothing to do with your code failing, though. Your formatter does support years outside the four digit range. It will print them with the necessary number of digits (up to 9, I believe, since it does not support dates in year 1 000 000 000) and with a sign (+ or -).

Documentation link

DateTimeFormatterBuilder.appendInstant(int)

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Unregistered user (0.5):
  • Filler text (0.5): 000000000
  • Low reputation (1):
Posted by: Manea Schmit