Java Data Type How to - Validate Date entry as format dd-MM-yyyy








Question

We would like to know how to validate Date entry as format dd-MM-yyyy.

Answer

import java.text.SimpleDateFormat;
// w  ww  .j av a  2s .  com
public class Main {
  public static void main(String[] args) throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    // Prints a value in 2014
    System.out.println(format.parse("16-16-2013"));
    format.setLenient(false);
    // Throws an exception
    System.out.println(format.parse("16-16-2013"));
  }
}

The code above generates the following result.