Java Data Type How to - Parse the input date based on the format that it is matched








Question

We would like to know how to parse the input date based on the format that it is matched.

Answer

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*from  ww w .j a  va  2  s . com*/
public class Main {
  public static void main(String[] args) {
    String[] tests = { "01/23/1983", "1/23/1983", "asdf/3/2" };

    String formatString = "MM/dd/yyyy";

    SimpleDateFormat sdf = new SimpleDateFormat(formatString);

    for (String test : tests) {
      Date date = null;
      try {
        date = sdf.parse(test);
      } catch (ParseException e) {
        e.printStackTrace();
      }
      System.out.println(date);
    }
  }
}

The code above generates the following result.