Date and time formats are strange, and when you do data aggregation related items, you will need to identify various datetime formats (because the data source is widely uncontrolled) and then convert to a standard format or date type.
I previously saw a colleague of a time analytic method, at that time felt already very good, later on-line search found this method in the search results appear many times, the source is not clear. I am because the project needs more accurate identification date time string, so I slowly improve the original method, the following is the improved method, the Java language implementation, as long as the logic, it should be easy to translate into other languages.
1 /**2 * Parse most common date formats <br/>
3 *@paramDatestr the string to parse5 * @returntime object, the parse failure is empty6 */7 Public StaticDate parsedate (String datestr) {8 if(Stringutil.isblank (datestr)) {9 return NULL;Ten } OneString parse =Datestr; ADateFormat format =NULL; -Parse = Parse.replacefirst ("^ (19|20) {1}[0-9]{2} ([^0-9]?)", "yyyy$2"); -Parse = Parse.replacefirst ("^[0-9]{2} ([^0-9]?)", "yy$1"); theParse = Parse.replacefirst ("([^0-9]?) (1{1}[0-2]{1}|0?) [0-9] {1}) ([^0-9]?) "," $1mm$3 "); -Parse = Parse.replacefirst ("([^0-9]?) (3{1}[0-1]{1}| [0-2]? [0-9] {1}) ([^0-9]?) "," $1dd$3 "); -Parse = Parse.replacefirst ("([^0-9]?) (2[0-3]{1}| [0-1]? [0-9] {1}) ([^0-9]?) "," $1hh$3 "); -Parse = Parse.replacefirst ("([^0-9]?) [0-5]? [0-9] {1} ([^0-9]?) "," $1mm$2 "); +Parse = Parse.replacefirst ("([^0-9]?) [0-5]? [0-9] {1} ([^0-9]?) "," $1ss$2 "); - Try { +Format =NewSimpleDateFormat (parse); ADate Date =Format.parse (DATESTR); atLog.debug ("Raw string:" +datestr+ ", judging format:" +parse+ ", parse Result:" +doformatdate (date, formatter_l)); - returndate; -}Catch(Exception e) { - if(!log.isdebugenabled ()) { -Log.error ("Date resolution Error:" +parse+ "-" +datestr); - } inLog.debug ("Date resolution Error:" +parse+ "-" +Datestr, E); - } to return NULL; +}
Technical Notes-Date time string parsing and recognition