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

后端 未结 5 2010
难免孤独
难免孤独 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:22

    Thanks @Teetoo. That helped me to find the solution to my problem:

    If I want the parse function to match the pattern exactly I have to set "lenient" (SimpleDateFormat.setLenient) of my SimpleDateFormat to false:

    SimpleDateFormat sdf = new SimpleDateFormat("d.M.y");
    sdf.setLenient(false);
    SimpleDateFormat sdf2 = new SimpleDateFormat("d-M-y");
    sdf2.setLenient(false);
    SimpleDateFormat sdf3 = new SimpleDateFormat("y-M-d");
    sdf3.setLenient(false);
    

    This will still parse the date if I only use one pattern letter for each segment but it will recognize that 2013 can't be the day and therefore it does not match the second pattern. In combination with a length check I recive exactly what I want.

提交回复
热议问题