SimpleDateFormat and parsing: parse doesn't fail with wrong input string date

后端 未结 1 389
自闭症患者
自闭症患者 2020-12-21 15:00

I\'m using

java.util.Date date;
SimpleDateFormat format = new SimpleDateFormat(\"dd/MM/yyyy\");
try {
  date = sdf.parse(inputString);
} catch (ParseExceptio         


        
相关标签:
1条回答
  • 2020-12-21 15:37

    Set the Leniency bit:

    public void setLenient(boolean lenient)
    

    Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

    The following code:

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    public class Tester {
        public static void main(String[] argv) {
            java.util.Date date;
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    
            // Lenient
            try {
                date = sdf.parse("40/02/2013");
                System.out.println("Lenient date is :                  "+date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
    
            // Rigorous
            sdf.setLenient(false);
    
            try {
                date = sdf.parse("40/02/2013");
                System.out.println("Rigorous date (won't be printed!): "+date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    Gives:

    Lenient date is :                  Tue Mar 12 00:00:00 IST 2013
    java.text.ParseException: Unparseable date: "40/02/2013"
        at java.text.DateFormat.parse(DateFormat.java:357)
    

    Notes

    1. When in doubt about a Java class, reading the class documentation should be your first step. I didn't know the answer to your question, I just Googled the class, clicked on the parse method link and noted the See Also part. You should always search first, and mention your findings in the question
    2. Lenient dates have a respectable history of bypassing censorship and inspire children's' imagination.
    0 讨论(0)
提交回复
热议问题