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

允我心安 提交于 2019-11-29 15:43:50
Adam Matan

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!