SimpleDateFormat.parse() ignores the number of characters in pattern

后端 未结 5 2013
难免孤独
难免孤独 2020-11-28 16:35

I\'m trying to parse a date String which can have tree different formats. Even though the String should not match the second pattern it somehow does and therefore returns a

5条回答
  •  天涯浪人
    2020-11-28 17:10

    A workaround could be to test the yyyy-MM-dd format with a regex:

    public static Date parseDate(String dateString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
    
        Date parsedDate;
        try {
            if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) {
                parsedDate = sdf3.parse(dateString);
            } else {
                throw new ParseException("", 0);
            }
        } catch (ParseException ex) {
            try {
                parsedDate = sdf2.parse(dateString);
            } catch (ParseException ex2) {
                parsedDate = sdf.parse(dateString);
            }
        }
        return parsedDate;
    }
    

提交回复
热议问题