我需要验证字符串是否为ISODateTimeFormat.dateTimeNoMillis()格式。

final DateTimeFormatter dateHourMinuteSecondFormatter =ISODateTimeFormat.dateTimeNoMillis();
String s = "2012-W12-12";
try {
        dateHourMinuteSecondFormatter.parseDateTime(s);
    } catch (IllegalArgumentException e) {
        e.setMessage("exception thrown);
    }


它应该引发异常,因为日期格式错误,但不是。
还有什么需要补充的吗?

最佳答案

不,您不需要做任何其他事情。

我怀疑实际上是在抛出示例,但是您的消息诊断不正确。对于Joda Time 2.1,这当然对我来说失败了:

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {

    public static void main(String[] args) throws Exception {
        DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis();
        String s = "2012-W12-12";
        try {
            DateTime dt = formatter.parseDateTime(s);
            System.out.println(dt);
        } catch (IllegalArgumentException e) {
            System.out.println(e);
        }
    }
}


输出:

java.lang.IllegalArgumentException: Invalid format: "2012-W12-12" is malformed
at "W12-12"

07-28 01:01