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
best way to check if a string is a valid date
Moderator: General Moderators
-
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
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.
- 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
aceconcepts did you bother to read his post? cause he already mentioned checkdate().
bjbasanes, you may want to check out these: explode(), strtotime().
bjbasanes, you may want to check out these: explode(), strtotime().
- 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
Hi bjbasanes,
What you could do is stick with checkdate() and simply prepare the date so that checkdate() can be utilised:
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...
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
}
Re: best way to check if a string is a valid date
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
@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