在我看來,綁定到類型爲LocalDate
的屬性的Spring註釋@DateTimeFormat將導致Spring選擇JodaTime-Formatter,而不是標準格式化程序,否則Spring將無法成功地將任何輸入字符串解析爲對象LocalDate
。該聲明在Spring source code的分析上完成(參見方法getParser(DateTimeFormat annotation, Class<?> fieldType)
的實施)。
如果是這樣那麼問題仍然是爲什麼你變通和解決方案「DD.MM.YY」能夠解析兩位數年以及正常四位數年。答案可以在Joda的資料和文件中找到。
來源提取org.joda.time.format.DateTimeFormat(JodaTime的格局分析私有方法parsePatternTo(DateTimeFormatterBuilder builder, String pattern)
完成):
case 'y': // year (number)
case 'Y': // year of era (number)
if (tokenLen == 2) {
boolean lenientParse = true;
// Peek ahead to next token.
if (i + 1 < length) {
indexRef[0]++;
if (isNumericToken(parseToken(pattern, indexRef))) {
// If next token is a number, cannot support
// lenient parse, because it will consume digits that it should not.
lenientParse = false;
}
indexRef[0]--;
}
// Use pivots which are compatible with SimpleDateFormat.
switch (c) {
case 'x':
builder.appendTwoDigitWeekyear(new DateTime().getWeekyear() - 30, lenientParse);
break;
case 'y':
case 'Y':
default:
builder.appendTwoDigitYear(new DateTime().getYear() - 30, lenientParse);
break;
}
因此,我們認識到,JodaTime轉換模式表達式「YY」的呼叫Builder的方法appendTwoDigitYear()
與參數lenientParse設置爲true
。有趣的是,選擇的關鍵年偏離了通常的Joda設置(+/- 50年),即(-80/+ 20年)。
在Javadoc of mentioned builder-method這是說:
「lenientParse - 如果爲true,如果數字計數而不是兩個,它被視爲一個絕對的一年」
這充分解釋了爲什麼「dd.mm. yy「也可以解析兩位數年份和四位數年份。
我認爲問題是關於JodaTime,不僅是'java.util.Date'。 –