Java Data Type How to - Fail parse with wrong input string date SimpleDateFormat and parsing








Question

We would like to know how to fail parse with wrong input string date SimpleDateFormat and parsing.

Answer

public void setLenient(boolean lenient) specifies 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.

import java.text.ParseException;
import java.text.SimpleDateFormat;
//from   ww  w  .j a  v  a2  s  .  co  m
public class Main {
  public static void main(String[] argv) {
    java.util.Date date;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    // Lenient
    try {
      date = sdf.parse("40/02/2015");
      System.out.println("Lenient date is :                  " + date);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    // Rigorous
    sdf.setLenient(false);

    try {
      date = sdf.parse("40/02/2015");
      System.out.println("Rigorous date (won't be printed!): " + date);
    } catch (ParseException e) {
      e.printStackTrace();
    }

  }
}

The code above generates the following result.