static final java . util . Date parseDate ( String formatted ) { if ( formatted == null || formatted . trim ( ) . equals ( "" ) ) return null ; try { DatatypeFactory factory = DatatypeFactory . newInstance ( ) ; XMLGregorianCalendar calendar = factory . newXMLGregorianCalendar ( formatted ) ; return calendar . toGregorianCalendar ( ) . getTime ( ) ; } catch ( Exception e ) { Matcher matcher = PATTERN_DD_MM_YYYY . matcher ( formatted ) ; // Try matching dd.MM.yyyy date formats first if ( matcher . find ( ) ) { String yyyy = matcher . group ( 3 ) ; String mm = matcher . group ( 2 ) ; String dd = matcher . group ( 1 ) ; String hh = defaultIfEmpty ( matcher . group ( 4 ) , "0" ) ; String min = defaultIfEmpty ( matcher . group ( 5 ) , "0" ) ; String ss = defaultIfEmpty ( matcher . group ( 6 ) , "0" ) ; String ms = defaultIfEmpty ( matcher . group ( 7 ) , "0" ) ; return getDate ( Integer . parseInt ( yyyy ) , Integer . parseInt ( mm ) , Integer . parseInt ( dd ) , Integer . parseInt ( hh ) , Integer . parseInt ( min ) , Integer . parseInt ( ss ) , Integer . parseInt ( ms ) ) ; } // Then try matching yyyy-MM-dd date formats else { Matcher matcher2 = PATTERN_YYYY_MM_DD . matcher ( formatted ) ; if ( matcher2 . find ( ) ) { String yyyy = matcher2 . group ( 1 ) ; String mm = defaultIfEmpty ( matcher2 . group ( 2 ) , "1" ) ; String dd = defaultIfEmpty ( matcher2 . group ( 3 ) , "1" ) ; String hh = defaultIfEmpty ( matcher2 . group ( 4 ) , "0" ) ; String min = defaultIfEmpty ( matcher2 . group ( 5 ) , "0" ) ; String ss = defaultIfEmpty ( matcher2 . group ( 6 ) , "0" ) ; String ms = defaultIfEmpty ( matcher2 . group ( 7 ) , "0" ) ; return getDate ( Integer . parseInt ( yyyy ) , Integer . parseInt ( mm ) , Integer . parseInt ( dd ) , Integer . parseInt ( hh ) , Integer . parseInt ( min ) , Integer . parseInt ( ss ) , Integer . parseInt ( ms ) ) ; } // Finally, try matching plain timestamps else { try { return new Date ( Long . parseLong ( formatted ) ) ; } catch ( NumberFormatException ignore ) { return null ; } } } } }
Parse any date format