Full Version: Date Validation using SimpleDateFormat()
Dream.In.Code > Programming Tutorials > Java Tutorials
fyrestorm
I was told that the JDK class SimpleDateFormat() might be useful for me to use in validating dates for a program that I'm working on.

Unfortunately for me, the documentation was crummy and it took a while to figure out what I needed to do. Fortunately for all that are reading this, after many hours of pain on my end, I can now write a tutorial for all the world to see.

This is very elementary in that it will only check to see if the date supplied is in the proper fomat that meets your specifications and it will check to see if the date is a proper date, meaning that someone can't try to enter a date such as 02/30/06.

In the future, I may add more robustness to this tutorial, but as it stands, this is all that I needed for my current assignment and I know that there are a number of other students stuggling with this so I thought it would be beneficial to post this tutorial as it is.

CODE

// date validation using SimpleDateFormat
// it will take a string and make sure it's in the proper
// format as defined by you, and it will also make sure that
// it's a legal date

public boolean isValidDate(String date)
{
   // set date format, this can be changed to whatever format
   // you want, MM-dd-yyyy, MM.dd.yyyy, dd.MM.yyyy etc.
   // you can read more about it here:
   // http://java.sun.com/j2se/1.4.2/docs/api/index.html
   
   SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
   
   // declare and initialize testDate variable, this is what will hold
   // our converted string
   
   Date testDate = null;

   // we will now try to parse the string into date form
   try
   {
     testDate = sdf.parse(date);
   }

   // if the format of the string provided doesn't match the format we
   // declared in SimpleDateFormat() we will get an exception

   catch (ParseException e)
   {
     errorMessage = "the date you provided is in an invalid date" +
                             " format.";
     return false;
   }

   // dateformat.parse will accept any date as long as it's in the format
   // you defined, it simply rolls dates over, for example, december 32
   // becomes jan 1 and december 0 becomes november 30
   // This statement will make sure that once the string
   // has been checked for proper formatting that the date is still the
   // date that was entered, if it's not, we assume that the date is invalid

   if (!sdf.format(testDate).equals(date))
   {
     errorMessage = "The date that you provided is invalid.";
     return false;
   }
   
   // if we make it to here without getting an error it is assumed that
   // the date was a valid one and that it's in the proper format

   return true;

} // end isValidDate
eLliDKraM
It's short and it gets to the point. Even my dumbass understood it, good tutorial.
symbol
Hi, well done for writing the code! i am in a similiar situation to you, i am trying to validate a date (birthday) field which gets input into a mysql database.

the only problem i am having is how do you implement the code to work with the date field?

i have copied the code and inserted it into my code, changed the date format to yyyy-MM-dd as that is how i am doing it.

simply, how do i get it to work? sad.gif

i am getting the date from a text field:

CODE

<input type="text" value="1900-01-01" name="birthday"  size=20>
fyrestorm
you need to call the function when you want to validate it, let's say when the user pushes the submit button (i'm assuming that you're using a form)

CODE

if(!isValidDate(birthday))
{
//do something here
}


additionally, since it looks like you're using a form, i'd suggest using a select option for the month, and day and year, because you can then bypass the validation because theoretically they should all be acceptable values as defined by the select box...
ralph.bean
While validation on the backend is critical, I was working on the same problem today and found this to be most helpful.
Hasenpfote
Another way would be the usage of a non-lenient calendar:

CODE

GregorianCalendar cal = new GregorianCalendar();
cal.setLenient(false);
cal.set(Calendar.YEAR, getBirthYear());
cal.set(Calendar.MONTH, getBirthMonth());
cal.set(Calendar.DAY_OF_MONTH, getBirthDay());

try {
  //This is important!!!! Look at javadoc of calendar
  cal.getTimeInMillis();
} catch (Exception e) {
//will be thrown, if the date is not valid
//handle error
}



I think this is easier if you have your date build from mulitple fields.
razom
how to make it easier to understand ?
hemanthjava
Here is a nice DATE UTILITY, I found in http://www.freejavaguide.com which does many many things other then Date Validation.

CODE

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtility {
    
/* Add Day/Month/Year to a Date
add() is used to add  values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/
    public static void addToDate(){
        System.out.println("In the ADD Operation");
    //    String DATE_FORMAT = "yyyy-MM-dd";
        String DATE_FORMAT = "dd-MM-yyyy";        //Refer Java DOCS for formats
        java.text.SimpleDateFormat sdf =  new java.text.SimpleDateFormat(DATE_FORMAT);
        Calendar c1 = Calendar.getInstance();
        Date d1 = new Date();
        System.out.println("Todays date in Calendar Format : "+c1);
        System.out.println("c1.getTime() : "+c1.getTime());
        System.out.println("c1.get(Calendar.YEAR): " + c1.get(Calendar.YEAR));
        System.out.println("Todays date in Date Format : "+d1);
        c1.set(1999,0 ,20);         //(year,month,date)
        System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());
        c1.add(Calendar.DATE,40);
        System.out.println("Date + 20 days is : " + sdf.format(c1.getTime()));
        System.out.println();
        System.out.println();
    }
    
    
/*Substract Day/Month/Year to a Date
    roll() is used to substract values to a Calendar object.
    You specify which Calendar field is to be affected by the operation
    (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
    
    Note: To substract, simply use a negative argument.
    roll() does the same thing except you specify if you want to roll up (add 1)
    or roll down (substract 1) to the specified Calendar field. The operation only
    affects the specified field while add() adjusts other Calendar fields.
    See the following example, roll() makes january rolls to december in the same
    year while add() substract the YEAR field for the correct result

*/
    
    public static void subToDate(){
        System.out.println("In the SUB Operation");
        String DATE_FORMAT = "dd-MM-yyyy";
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
        Calendar c1 = Calendar.getInstance();
        c1.set(1999, 0 , 20);
        System.out.println("Date is : " + sdf.format(c1.getTime()));
        
        // roll down, substract 1 month
        c1.roll(Calendar.MONTH, false);
        System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime()));

        c1.set(1999, 0 , 20);
        System.out.println("Date is : " + sdf.format(c1.getTime()));
        c1.add(Calendar.MONTH, -1);
        // substract 1 month
        System.out.println("Date minus 1 month : " + sdf.format(c1.getTime()));
        System.out.println();
        System.out.println();
    }
    
    public static void daysBetween2Dates(){
        Calendar c1 = Calendar.getInstance();     //new GregorianCalendar();
        Calendar c2 = Calendar.getInstance();     //new GregorianCalendar();
        c1.set(1999, 0 , 20);
        c2.set(1999, 0 , 22);
        System.out.println("Days Between "+c1.getTime()+"\t"+ c2.getTime()+" is");
        System.out.println((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000));
        System.out.println();
        System.out.println();
    }
    
    public static void daysInMonth() {
        Calendar c1 = Calendar.getInstance();     //new GregorianCalendar();
        c1.set(1999, 6 , 20);
        int year = c1.get(Calendar.YEAR);
        int month = c1.get(Calendar.MONTH);
//        int days = c1.get(Calendar.DATE);
        int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
        daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
        System.out.println("Days in "+month+"th month for year "+year+" is "+ daysInMonths[c1.get(Calendar.MONTH)]);
        System.out.println();
        System.out.println();
    }
    
    public static void getDayofTheDate() {
        Date d1 = new Date();
        String day = null;
        DateFormat f = new SimpleDateFormat("EEEE");
        try {
         day = f.format(d1);
        }
        catch(Exception e) {
          e.printStackTrace();
        }
        System.out.println("The dat for "+d1+" is "+day);
        System.out.println();
        System.out.println();
    }
    
    public static void validateAGivenDate() {
        String dt = "20011223";  
        String invalidDt = "20031315";
        String dateformat = "yyyyMMdd";  
        Date dt1=null , dt2=null;
        try {    
            SimpleDateFormat sdf = new SimpleDateFormat(dateformat);    
            sdf.setLenient(false);    
            dt1 = sdf.parse(dt);  
            dt2 = sdf.parse(invalidDt);  
            System.out.println("Date is ok = " + dt1 + "(" + dt + ")");    
        }  
        catch (ParseException e) {    
            System.out.println(e.getMessage());
        }  
        catch (IllegalArgumentException e) {    
            System.out.println("Invalid date");    
        }
        System.out.println();
        System.out.println();
    }
    
    public static void compare2Dates(){
        SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        
        c1.set(2000, 02, 15);
        c2.set(2001, 02, 15);
        
        System.out.print(fm.format(c1.getTime())+" is ");
        if(c1.before(c2)){
            System.out.println("less than "+c2.getTime());
        }else if(c1.after(c2)){
            System.out.println("greater than "+c2.getTime());
        }else if(c1.equals(c2)){
            System.out.println("is equal to "+fm.format(c2.getTime()));
        }
        System.out.println();
        System.out.println();
    }

    public static boolean isLeapYear(int year){
         if((year%100 != 0) || (year%400 == 0)){
             return true;
         }
         return false;
    }

    public static void main(String args[]){
        addToDate();
        subToDate();
        daysBetween2Dates();    //The "right" way would be to compute the julian day number of both dates and then do the substraction.
        daysInMonth();
        validateAGivenDate();
        compare2Dates();
        getDayofTheDate();
    }
    
}


For More code simply check http://www.freejavaguide.com
oubless
QUOTE(fyrestorm @ 10 Mar, 2006 - 07:42 AM) *

you need to call the function when you want to validate it, let's say when the user pushes the submit button (i'm assuming that you're using a form)

CODE

if(!isValidDate(birthday))
{
//do something here
}


additionally, since it looks like you're using a form, i'd suggest using a select option for the month, and day and year, because you can then bypass the validation because theoretically they should all be acceptable values as defined by the select box...

NEVER EVER TRUST A USER INPUT!!! EVER!!!
There is nothing more simple than sending different input. About dates - I would suggest to use a javascript calendar/datepicker unless javascript is forbidden. I would recommend jQuery UI Datepicker. You need to write a method to translate your Java date format string to its date format string, but its worth the work.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.