java中的日期验证

时间:2013-01-14 20:08:09

标签: java date jodatime

我需要验证字符串以查看它是否代表ISO格式日期,如果不是,我需要抛出用户定义的异常。

我有这行代码,

DateTimeFormatter formatter = ISODateTimeFormat.date();

如何使用此格式化程序验证字符串?

2 个答案:

答案 0 :(得分:1)

尝试使用formatter.parseDateTime()方法解析它。

当字符串不是有效日期时,它将抛出IllegalArgumentException。当你想抛出自己的异常时,只需抓住它并抛出另一个异常。

答案 1 :(得分:0)

您可以尝试使用您已获得的formatter进行解析,捕获IllegalArgumentException,然后抛出用户定义的异常:

try {
    formatter.parseMillis(stringBeingValidated); // You can use another parseXYZ method here
} catch (IllegalArgumentException iae) {
    throw new CustomException(iae.getMessage()); // The getMessage() call is only an example.
}