Real'sHowTo AddThis Feed Button
Custom Search

Validate a dateTag(s): Date and Time


Using DateFormat

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
     */
  }
}
Using SimpleDateFormat
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
     */
  }
}

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


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]