joda date DateTimeFormatterBuilder追加不起作用

时间:2014-05-22 08:26:16

标签: java jodatime date-format

代码优先。

@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

一切都失败了。难道我做错了什么?它看起来应该没问题。

1 个答案:

答案 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();