SimpleDateFormat giving wrong date instead of error

后端 未结 3 2035
爱一瞬间的悲伤
爱一瞬间的悲伤 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:40

    Set Lenient will work for most cases but if you wanna check the exact string pattern then this might help,

        String s = "03/6/1988";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            sdf.setLenient(false);
            Date d = sdf.parse(s);
            String s1 = sdf.format(d);
            if (s1.equals(s))
                System.out.println("Valid");
            else
                System.out.println("Invalid");
        } catch (ParseException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
    

    If you give the input as "03/06/1988" then you'll get valid result.

    0 讨论(0)
  • 2020-12-07 02:51

    Use DateFormat.setLenient(false) to tell the DateFormat/SimpleDateFormat that you want it to be strict.

    0 讨论(0)
  • 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?
    0 讨论(0)
提交回复
热议问题