如何在不使用Exception的情况下检查Date是否符合特定的DateFormat?

问题描述:

我知道parse()可用于知道有效日期是否符合特定格式.但这会在发生故障的情况下引发异常.我只想确认日期是否为特定格式.特别是我需要从此比较中得出布尔值.如何在Java中实现?

I am aware that parse() can be used for knowing if the valid date conforms to a specific format. But that throws exception in case of a failure. I wanted just to verify if the date is of a specific format. Especially I need a boolean result from this comparison. How to achieve that in Java?

我想知道为什么这里没有人知道使用 ParsePosition 进行标准验证.基于异常逻辑的编程或多或少是邪恶的.

I am wondering why nobody here knows following standard validation using ParsePosition. Programming based on exception logic is more or less evil.

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(false);
ParsePosition pp = new ParsePosition(0);
java.util.Date d = sdf.parse("02/29/2015", pp);

if (d == null) {
    System.out.println("Error occurred at position: " + pp.getErrorIndex());
    return false;
} else {
    return true; // valid
}

请注意,使用严格模式很重要!

有点超出问题的范围,但很有趣:

A little bit out of scope of the question but interesting:

新的 java.time 库(JSR-310)

The new java.time-library (JSR-310) does force the user to code against exceptions - a clear regression compared with 'SimpleDateFormat`. The problem of catching exceptions is generally bad performance which can be relevant if you parse bulk data with lower quality.