Validate a dateTag(s): Date and Time


Using SimpleDateFormat
import java.text.*;
import java.util.Date;

public class DateUtils {
   private DateUtils() {   }

   public static boolean isValidDateStr(String strdate, String format) {
      Date date = null;
      try {
          SimpleDateFormat sdf = new SimpleDateFormat(format);
          date = sdf.parse(strdate);
          if (!strdate.equals(sdf.format(date))) {
              date = null;
          }
      } catch (ParseException ex) {
          ex.printStackTrace();
      }
      return date != null;
  }

  public static void main(String[] args) {
    System.out.println(" 1900-12-13 valid ? "
        + DateUtils.isValidDateStr("1900-12-13","yyyy-MM-dd"));

    // "1990-12/13" throws a ParseException
    System.out.println(" 1900-12/13 valid ? "
        + DateUtils.isValidDateStr("1900-12/13","yyyy-MM-dd"));
    // "1990-13-12" throws a IllegalArgumentException
    System.out.println(" 1900-13-12 valid ? "
        + DateUtils.isValidDateStr("1900-13-12","yyyy-MM-dd"));
    /*
     * output :
     *  1900-12-13 valid ? true
     *  1900-12/13 valid ? false
     *  1900-13-12 valid ? false
     */
  }
}

Using GregorianCalendar
import java.util.*;

public class jtest {
    public static void main(String args[]) {
        try {
            GregorianCalendar gc = new GregorianCalendar();
            gc.setLenient(false);        // must do this
            gc.set(GregorianCalendar.YEAR, 2003);
            gc.set(GregorianCalendar.MONTH, 42);// invalid month
            gc.set(GregorianCalendar.DATE, 1);

            gc.getTime(); // exception thrown here
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

blog comments powered by Disqus