代码优先。
@Test
public void testDateFormat()
{
// this is ok
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("2014-5-15 20:00:00");
DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime("2014-5-15");
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss")
.appendPattern("yyyy-MM-dd")
// ues these way is also failed.
//.append(DateTimeFormat.forPattern("xxxx"))
//.append(DateTimeFormat.forPattern("xxxx").getParser())
.toFormatter();
try
{
formatter.parseLocalDateTime("2014-5-15 20:00:00");
}catch (Exception ignored){System.out.println("Failed A");}
try
{
formatter.parseLocalDateTime("2014-05-15 20:00:00");
}catch (Exception ignored){System.out.println("Failed B");}
try
{
formatter.parseLocalDateTime("2014-5-15");
}catch (Exception ignored){System.out.println("Failed C");}
try
{
formatter.parseLocalDateTime("2014-05-15");
}catch (Exception ignored){System.out.println("Failed D");}
}
输出
Failed A:Invalid format: "2014-5-15 20:00:00" is too short
Failed B:Invalid format: "2014-05-15 20:00:00" is too short
Failed C:Invalid format: "2014-5-15" is too short
Failed D:Invalid format: "2014-05-15" is too short
一切都失败了。难道我做错了什么?它看起来应该没问题。
答案 0 :(得分:2)
找到this
正确的方法。
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(null,
new DateTimeParser[]{DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").getParser()})
.toFormatter();