正则表达式太过分了
这里不需要棘手的正则表达式匹配。只需将日期时间文本解析为日期时间对象。
java.time
在您的示例中,仅使用了两种格式。所以尝试使用现代的 java.time 类来解析每一个。它们是相似的,一个是日期优先,另一个是时间优先。
DateTimeFormatter fDateTime = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
DateTimeFormatter fTimeDate = DateTimeFormatter.ofPattern( "HH:mm:ss uuuu-MM-dd" ) ;
首先,从字符串中提取前 19 个字符,以便仅关注日期时间数据。
解析,捕获DateTimeParseException。
LocalDateTime ldt = null ;
try{
if( Objects.isNull( ldt ) {
LocalDateTime ldt = LocalDateTime.parse( input , fDateTime ) ;
}
} catch ( DateTimeParseException e ) {
// Swallow this exception in this case.
}
try{
if( Objects.isNull( ldt ) {
LocalDateTime ldt = LocalDateTime.parse( input , fTimeDate ) ;
}
} catch ( DateTimeParseException e ) {
// Swallow this exception in this case.
}
// If still null at this point, then neither format above matched the input.
if( Objects.isNull( ldt ) {
// TODO: Deal with error condition, where we encountered data in unexpected format.
}
如果您想要仅日期而不需要时间,请提取 LocalDate 对象。
LocalDate ld = ldt.toLocalDate() ;
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。