I'm trying to format Instant
to String
with a specific format. Based on the question here Format Instant to String, I'm doing this -
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("YYYY-MM-DD'T'hh:mm'Z'")
.withZone(ZoneOffset.UTC);
// Fails for current time with error 'Field DayOfYear cannot be printed as the
// value 148 exceeds the maximum print width of 2'
LocalDateTime
.ofInstant(Instant.now(), ZoneOffset.UTC)
.format(DATE_TIME_FORMATTER);
// But works for smaller values of Instant
LocalDateTime
.ofInstant(Instant.ofEpochMilli(604800000), ZoneOffset.UTC)
.format(DATE_TIME_FORMATTER));
Any suggestions on why is this happening?
Thanks
withZone(ZoneId. systemDefault()); Instant instant = Instant. parse("2022-02-15T18:35:24.00Z"); String formattedInstant = formatter. format(instant); assertThat(formattedInstant).
The ISO_INSTANT formatter is a special case formatter designed to work with Instant . If you are using a ZonedDateTime you should use a different formatter, such as ISO_DATE_TIME or ISO_ZONED_DATE_TIME .
ISO_DATE_TIME. The ISO-like date-time formatter that formats or parses a date-time with the offset and zone if available, such as '2011-12-03T10:15:30', '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'. static DateTimeFormatter.
Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well. Implementation Requirements: This class is immutable and thread-safe.
Pattern YYYY-MM-DD'T'hh:mm'Z'
is wrong:
YYYY
- week-based-year wrong: use uuuu
year
MM
- month-of-yearDD
- day-of-year wrong: use dd
day-of-month
hh
- clock-hour-of-am-pm (1-12) without AM/PM you probably want HH
hour-of-day (0-23)
mm
- minute-of-hourIt's weird, because you even referenced a link that had the right pattern characters. Unless of course you thought upper- vs lower-case didn't matter, but if so, how did you think MM
(month) vs mm
(minute) worked?
You might want to actually read the documentation.
Take a look at the documentation of the DateTimeFormatter. So, D
stands for the day of the year, while d
is the day of the month, which is what you want.
Plus, there are several formats that are already defined. The one you want is almost like DateTimeFormatter.ISO_INSTANT
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With