How to parse dates in multiple formats using SimpleDateFormat

前端 未结 12 1697
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 08:41

I am trying to parse some dates that are coming out of a document. It would appear users have entered these dates in a similar but not exact format.

here are the for

12条回答
  •  旧巷少年郎
    2020-11-22 09:21

    This solution checks all the possible formats before throwing an exception. This solution is more convenient if you are trying to test for multiple date formats.

    Date extractTimestampInput(String strDate){
        final List dateFormats = Arrays.asList("yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd");    
    
        for(String format: dateFormats){
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            try{
                return sdf.parse(strDate);
            } catch (ParseException e) {
                 //intentionally empty
            }
        }
            throw new IllegalArgumentException("Invalid input for date. Given '"+strDate+"', expecting format yyyy-MM-dd HH:mm:ss.SSS or yyyy-MM-dd.");
    
    }
    

提交回复
热议问题