正则表达式是矫枉过正
对于日期时间的工作,不需要打扰regex.
只需尝试使用一种格式进行解析,捕获预期的异常.如果确实抛出了异常,请尝试使用其他格式进行解析.如果抛出异常,那么您知道输入意外地不是两种格式.
java.time
您正在使用现在由Java 8及更高版本内置的java.time框架取代的旧的麻烦的日期时间类.新课程的灵感来自非常成功的Joda-Time框架,旨在作为其继承者,在概念上类似但重新设计.由JSR 310定义.由ThreeTen-Extra项目扩展.见Oracle Tutorial.
LOCALDATE的
新类包括一个LocalDate,仅适用于没有时间的日期值.正是你需要的.
格式化程序
您的第一种格式可能是标准的ISO 8601格式,YYYY-MM-DD.默认情况下,此格式用于java.time.
如果由于输入与ISO 8601格式不匹配而导致第一次解析尝试失败,则抛出DateTimeParseException.
LocalDate localDate = null;
try {
localDate = LocalDate.parse( input ); // ISO 8601 formatter used implicitly.
} catch ( DateTimeParseException e ) {
// Exception means the input is not in ISO 8601 format.
}
另一种格式必须由与您使用SimpleDateFormat类似的编码模式指定.因此,如果我们从第一次尝试中捕获异常,请进行第二次解析尝试.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM-dd-yyyy" );
LocalDate localDate = null;
try {
localDate = LocalDate.parse( input );
} catch ( DateTimeParseException e ) {
// Exception means the input is not in ISO 8601 format.
// Try the other expected format.
try {
localDate = LocalDate.parse( input,formatter );
} catch ( DateTimeParseException e ) {
// FIXME: Unexpected input fit neither of our expected patterns.
}
}