Page 1 of 1

best way to check if a string is a valid date

Posted: Sun Apr 27, 2008 6:38 pm
by bjbasanes
Hi,

What would be the best way to check if a string is a valid date? On a page, users are allowed to enter dates as strings (ie "12/23/2008"). But in the code I have to check if the entered string is a valid date. I looked at the checkdate() function but it requires the month, date, and year to be separated already.

Thanks

Re: best way to check if a string is a valid date

Posted: Sun Apr 27, 2008 6:47 pm
by nowaydown1
Your best bet with this would probably be to use a regular expression to check against whatever format you accept (MM/DD/YYYY). If you do some googling you should be able to find a regex that meets your needs.

Re: best way to check if a string is a valid date

Posted: Sun Apr 27, 2008 7:00 pm
by aceconcepts

Re: best way to check if a string is a valid date

Posted: Mon Apr 28, 2008 3:20 am
by Oren
aceconcepts did you bother to read his post? cause he already mentioned checkdate().
bjbasanes, you may want to check out these: explode(), strtotime().

Re: best way to check if a string is a valid date

Posted: Mon Apr 28, 2008 3:35 am
by aceconcepts
Hi bjbasanes,

What you could do is stick with checkdate() and simply prepare the date so that checkdate() can be utilised:

Code: Select all

 
$strDate="12/23/2008";
 
//extract day, month and year
$expDate=explode("/", $strDate);
$day=$expDate[1];
$month=$expDate[0];
$year=$expDate[2];
 
//check date
if(checkdate($month, $day, $year))
{
   //valid
} else {
   //invalid
}
 
It's very very crude but should give some idea as to how you could code it. You would need additional checks - what if a different format was used i.e. day/month/year etc...

Re: best way to check if a string is a valid date

Posted: Mon Apr 28, 2008 11:16 pm
by bjbasanes
thank you for the replies guys..

@Oren > yeap I'm thinking strtotime() that would be the best way
@aceconcepts, @nowaydown1 > thank you for the ideas, I'll see on what would be better