I am trying to check a date format to see if I can check the data variable has certain format like MM-DD-YYYY. if not, then exit(). I am not sure how to check the format and would appreciate if any one can help me about it. Thanks...

$date=05/25/2010;    
if(XXXXX){
    // do something....
}

Comments

Thanks guys. I can't vote you guys yet. Vote me and make me to 15 reputation and i give u all +1..:D

Written by user401184

Accepted Answer

Use a regular expression, as others have suggested. The ones posted before will accept invalid dates such as 99/99/9999 however. Here's an improved regex (lifed from here)

$date_regex = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$!';
if (preg_match($date_regex, $date)) {
   // do something
}

It will only take valid dates and it will also accept different separators (such as 05.20.2002 and 05-02-2002).

If you ask me it's bad user experience to force them to enter a particular format. YOU can handle different formats using strtotime().

This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki