Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Instant to String with specific pattern

Tags:

java

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

like image 906
RandomQuestion Avatar asked May 27 '16 22:05

RandomQuestion


People also ask

How do I format an Instant string?

withZone(ZoneId. systemDefault()); Instant instant = Instant. parse("2022-02-15T18:35:24.00Z"); String formattedInstant = formatter. format(instant); assertThat(formattedInstant).

What is iso_instant?

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 .

What is DateTimeFormatter Iso_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.

Is Java time format DateTimeFormatter thread-safe?

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.


2 Answers

Pattern YYYY-MM-DD'T'hh:mm'Z' is wrong:

  • YYYY - week-based-year       wrong: use uuuu year
  • MM - month-of-year
  • DD - 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-hour

It'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.

like image 182
Andreas Avatar answered Nov 06 '22 16:11

Andreas


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.

like image 21
T. Claverie Avatar answered Nov 06 '22 17:11

T. Claverie