SimpleDateFormat giving wrong date instead of error

后端 未结 3 2055
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 02:24

I am using following pattern and date

Date : 13-13-2007

Pattern : dd-MM-yyyy

Output: Sun Jan 13 00:00:00 IST 2008 Or 2008-01-13 00:00:00.0

I

3条回答
  •  一个人的身影
    2020-12-07 02:58

    java.time

    I should like to contribute the modern answer. When this question was asked in 2011, it was reasonable to use SimpleDateFormat and Date. It isn’t anymore. Those classes were always poorly designed and were replaced by java.time, the modern Java date and time API, in 2014, so are now long outdated.

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
    
        String dateString = "13-13-2007";
        LocalDate date = LocalDate.parse(dateString, dateFormatter);
    

    This code gives the exception you had expected (and had good reason to expect):

    Exception in thread "main" java.time.format.DateTimeParseException: Text '13-13-2007' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13

    Please also notice and enjoy the precise and informative exception message.

    DateTimeFormatter has three so-called resolver styles, strict, smart and lenient. Smart is the default, and you will rarely need anything else. Use strict if you want to be sure to catch all invalid dates under all circumstances.

    Links

    • Oracle tutorial: Date Time explaining how to use java.time.
    • uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?

提交回复
热议问题