在java中验证日期

时间:2013-01-07 10:44:27

标签: java validation datetime

我正在使用NetBeans IDE 7.2。 我有两个单独的类newDateTest.javanewDateMethod.java,我目前正在使用我的方法类来验证我在测试类中使用的用户输入的日期。

到目前为止,在我的Test课程中,我有以下内容:

try
{
    Prompt ="please enter a date in the format dd-mm-yyyy";
    System.out.println(Prompt);
    String inputDate = in.next();
    isValid = newDateMethod.validDate(input, input, input);
    if (isValid){
        System.out.println("VALID DATE");

    } else {
        System.out.println("INVALID DATE");

    }

}catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println(oob);
}
}

但是我不知道如何在我的方法类中验证日期,因为我对Java很新。

任何人都可以找到解决方案吗?我被教导使用的那种东西是Date Formmater,但不确定这是否合适?如果是这样就不知道如何使用它

7 个答案:

答案 0 :(得分:12)

像这样:

Date date = null;
String inputDate = "07-01-2013";
try {
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
    formatter.setLenient(false);
    date = formatter.parse(inputDate);
} catch (ParseException e) { 
    e.printStackTrace();
}

答案 1 :(得分:3)

看看SimpleDateFormat.parse(...),并记得用try-catch包围。

答案 2 :(得分:1)

标准的JDK类是SimpleDateFormat

DateFormat fmt = new SimpleDateFormat("yourformathere");

// use fmt.parse() to check for validity

或者,我建议您使用Joda TimeDateTimeFormat

答案 3 :(得分:1)

您可以使用Apache commons例程包中的DateValidator,而不是依赖于往往具有较小性能开销的异常:

if (DateValidator.getInstance().validate(inputDate, "dd-MM-yyyy") != null) {
  // Date is valid
}
else {
  // Date is invalid
}

虽然小免责声明,我还没有看过validate方法的实现,但我不确定它是否使用了SimpleDateFormat ......

答案 4 :(得分:1)

java.time

我建议您使用 java.time(现代 Java 日期和时间 API)进行日期工作。与其他一些答案中使用的旧 SimpleDateFormat 类相比,它还为您提供了更精确的验证。

    String[] exampleInputStrings = { "07-01-2013", "07-01-017",
            "07-01-2ooo", "32-01-2017", "7-1-2013", "07-01-2013 blabla" };
    
    for (String inputDate : exampleInputStrings) {
        try {
            LocalDate date = LocalDate.parse(inputDate, DATE_FORMATTER);
            System.out.println(inputDate + ": valid date: " + date );
        } catch (DateTimeParseException dtpe) {
            System.out.println(inputDate + ": invalid date: " + dtpe.getMessage());
        }
    }

我的示例代码的输出是:

<块引用>
07-01-2013: valid date: 2013-01-07
07-01-017: invalid date: Text '07-01-017' could not be parsed at index 6
07-01-2ooo: invalid date: Text '07-01-2ooo' could not be parsed at index 6
32-01-2017: invalid date: Text '32-01-2017' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 32
7-1-2013: invalid date: Text '7-1-2013' could not be parsed at index 0
07-01-2013 blabla: invalid date: Text '07-01-2013 blabla' could not be parsed, unparsed text found at index 10

为了进行良好的验证,您可能应该添加范围检查。使用 isBefore 和/或 isAfterLocalDate 方法。

此外,如果您打算对日期做任何比验证日期更多的事情,您应该避免在程序中解析 LocalDate(而不是字符串)。

Oracle tutorial: Date Time 解释如何使用 java.time。

答案 5 :(得分:0)

您应该使用SimpleDateFormat.parse(String)方法。如果传递的日期格式错误,则抛出异常,在这种情况下返回false。

public boolean validateDate(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    try {
        sdf.parse(date);
        return true;
    }
    catch(ParseException ex) {
        return false;
    }
}

答案 6 :(得分:0)

一个人可以使用joda-time

DateTimeFormat.forPattern(INPUTED_DATE_FORMAT);
//one can also use it with locale
DateTimeFormat.forPattern(USER_DATE_FORMAT).withLocale(locale);
fmt.parseDateTime(INPUTED_DATE);

如果parseDateTime抛出IllegalArgumentException,则日期无效。

相关问题