best way to check if a string is a valid date

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bjbasanes
Forum Newbie
Posts: 2
Joined: Sun Apr 27, 2008 6:34 pm

best way to check if a string is a valid date

Post 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
nowaydown1
Forum Contributor
Posts: 169
Joined: Sun Apr 27, 2008 1:22 am

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

Post 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.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

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

Post by aceconcepts »

User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

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

Post 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().
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

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

Post 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...
bjbasanes
Forum Newbie
Posts: 2
Joined: Sun Apr 27, 2008 6:34 pm

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

Post 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
Post Reply