Java Data Type How to - Catch exception for Parsing String into Date








Question

We would like to know how to catch exception for Parsing String into Date.

Answer

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
// www .j  a  v a 2 s .  c o m
public class Main {
  public static void main(String[] args) {
    try {
      String str_date = "11-June-07";
      DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
      Date date = (Date) formatter.parse(str_date);
      System.out.println(date);
    } catch (ParseException e) {
      System.out.println("Exception :" + e);
    }
  }
}