Search code examples
javajsr310threetenbp

ThreeTen and parsing an Instant


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.


Solution

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