Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

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

I'm using

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

where inputString is a string in the dd/MM/yyyy format.

If the inputString is, for example, 40/02/2013, I would to obtain an error, instead the parse method returns the Date 12 March 2013 (12/03/2013). What I'm wronging?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...