Java - 检查日期是否对给定的dateformat有效

时间:2017-08-30 18:58:38

标签: java datetime simpledateformat

我有以下代码来检查给定日期是否有效

SimpleDateFormat fromformatter = new SimpleDateFormat("MMYY");
fromformatter.setLenient(false);

try {
    fromformatter.parse(dateString);
    valuesQuery.append("'" + dateString+ "',");
} catch (ParseException pe) {
    pe.printStackTrace();
    valuesQuery.append("'notDate" + dateString+ "',");
}

现在,当我得到dateString = "1803";不是有效日期时,不会抛出任何异常。此处使用的日期格式为MMYY

我做错了什么?

请注意,正则表达式不会对我有所帮助,因为日期格式会发生变化。

2 个答案:

答案 0 :(得分:1)

“mm”是分钟。请改用“MMyy”。没有异常被抛出,因为18是分钟的有效值。

SimpleDateFormat fromformatter = new SimpleDateFormat("MMyy");

请检查:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

答案 1 :(得分:1)

java.time

Use the modern java.time classes rather than the troublesome legacy date-time classes.

Specifically use the YearMonth to represent such values. It's WebTarget method will throw an exception for invalid input.

RequestEntity

TIP: If possible, use standard ISO 8601 formats rather than that peculiar format. For year-month that would be YYYY-MM such as RequestEntity.