2014-09-12 75 views
3

我正在使用ThreeTen並試圖格式化Instant。分開它會更容易,但我很好奇,應該工作嗎?一切從我讀過的即時需要語法分析,並使用該模式的所有組件:ThreeTen並解析即時

@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; 
    } 
} 

錯誤:org.threeten.bp.temporal.UnsupportedTemporalTypeException:不支持的領域:工作日

DD是DayofWeek的一天而不是DayofWeek。大概扔了一個紅鯡魚,但它似乎很奇怪。

回答

3

模式字母「Y」表示ThreeTen-Backport和JSR-310(這意味着Joda-Time中的時代年代)以周爲基準年。爲了計算以周爲基礎的年份,需要星期幾,因此是錯誤。

請注意,Instant無法爲您嘗試創建的格式化程序提供字段。只有ZonedDateTime,LocalDateTimeOffsetDateTime可以。 Instant是一種特殊情況,必須使用DateTimeFormatter.ISO_INSTANT或類似的格式。

1

作出明確JodaStephen的回答是:

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

應該

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

代替。

另外,代替

Instant instant = Instant.now();

LocalDateTime localDateTime = LocalDateTime.now();

...然後傳遞到format()代替。

既然InstantLocalDateTime實現TemporalAccessor,這是DateTimeFormatter.format()接受什麼,那麼其餘的代碼應該按原樣工作。