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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.