4

I'm using ThreeTen and attempted to format an Instant. Would be easier to just split it but I'm curious, should this work? From everything I've read Instant should be parse-able, and with all the components of the pattern:

@Test
public void testInstants()  {
    Instant instant = Instant.now();
    String dbDatePattern = "YYYY-MM-dd HH:mm:ss.SSS";
    try {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dbDatePattern);
        String dbDate = formatter.format(instant);
    } catch (Exception ex) {
        int dosomething = 1;
    }
}

Error: org.threeten.bp.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfWeek

dd is day of month not DayofWeek. Probably getting tossed a red herring, but it seems odd.

Jonik
  • 80,077
  • 70
  • 264
  • 372
user1351848
  • 127
  • 1
  • 1
  • 9

2 Answers2

4

The pattern letter "Y" means week-based-year in ThreeTen-Backport and JSR-310 (it meant year-of-era in Joda-Time). In order to calculate the week-based-year, the day-of-week is needed, hence the error.

Note that an Instant cannot supply fields for the formatter you are trying to create. Only a ZonedDateTime, LocalDateTime or OffsetDateTime can. An Instant is a special case that must be formatted using DateTimeFormatter.ISO_INSTANT or similar.

JodaStephen
  • 60,927
  • 15
  • 95
  • 117
2

To make explicit JodaStephen's answer:

String dbDatePattern = "YYYY-MM-dd HH:mm:ss.SSS"; (uppercase YYYY)

should be

String dbDatePattern = "yyyy-MM-dd HH:mm:ss.SSS"; (lowercase yyyy)

instead.

Also, instead of

Instant instant = Instant.now();

do

LocalDateTime localDateTime = LocalDateTime.now();

...and then pass that to format() instead.

Since both Instant and LocalDateTime implement TemporalAccessor, which is what DateTimeFormatter.format() accepts, the rest of your code should work as-is.

László van den Hoek
  • 3,955
  • 1
  • 23
  • 28