正規表達式是矯枉過正
對于日期時間的工作,不需要打擾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.
}
}