12小时格式的时间验证

时间:2012-06-28 05:01:25

标签: java regex struts-1

在请假申请表中,有两个时间字段'From'和'To'。当我说时间字段中的12:30 PM和时间字段中的下午1:30时,验证结果显示'To'时间应该大于'From'时间。是否有任何简单的验证(可能是正则表达式)可用于验证这一点,因此它应该以12小时格式接受此时间。

任何建议都会很明显。

感谢。

2 个答案:

答案 0 :(得分:1)

确保您小心处理过境日/周/月/年/ ...边界。

您可能有兴趣看一下http://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time

答案 1 :(得分:1)

您可以使用SimpleDateFormatter作为此示例:

DateFormat formatter = new SimpleDateFormat("hh:mm a");
Date from = (Date)formatter.parse(fromText);
Date to= (Date)formatter.parse(toText);

if (from.after(to)) {
    // Show message as you want.
    return;
}

如果你想验证,只需在parse()方法上添加try / catch,然后显示消息。

try {
    Date from = (Date)formatter.parse(fromText);
}
catch(Exception e) {
    // Show message;
    return;
}
相关问题