Validate a date

From CodeCodex

Revision as of 07:24, 28 August 2009 by Techmind (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Implementations

Java

<highlightsyntax language="java122"> import java.text.*;

public class DateUtils {

 public static boolean isValidDateStr(String date) {
   try {
    DateFormat df =
      DateFormat.getDateInstance
        (DateFormat.SHORT); // YYYY-MM-DD
    df.setLenient(false);   // this is important!
    df.parse(date);
   }
   catch (ParseException e) {
    return false;
   }
   catch (IllegalArgumentException e) {
    return false;
   }
   return true;
 }
 
 public static void main(String[] args) {
   System.out.println(" 1900-12-13 valid ? " 
       + DateUtils.isValidDateStr("1900-12-13"));
   // "1990-12/13" throws a ParseException
   System.out.println(" 1900-12/13 valid ? " 
       + DateUtils.isValidDateStr("1900-12/13"));
   // "1990-13-12" throws a IllegalArgumentException
   System.out.println(" 1900-13-12 valid ? " 
       + DateUtils.isValidDateStr("1900-13-12"));
   /*
    * output :
    *  1900-12-13 valid ? true
    *  1900-12/13 valid ? false
    *  1900-13-12 valid ? false
    */
 }

}


</highlightsyntax> Using SimpleDateFormat <highlightsyntax language="java122"> package com.rgagnon.howto;

import java.text.*;

public class DateUtils {

 public static boolean isValidDateStr(String date, String format) {
   try {
     SimpleDateFormat sdf = new SimpleDateFormat(format);
     sdf.setLenient(false);
     sdf.parse(date);
   }
   catch (ParseException e) {
     return false;
   }
   catch (IllegalArgumentException e) {
     return false;
   }
   return true;
   }
 
 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
    */
 }

}


</highlightsyntax> Using GregorianCalendar <highlightsyntax language="java122"> 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();
       }
   }

}

</highlightsyntax>