Reputation: 37
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....
}
Upvotes: 3
Views: 767
Reputation: 1596
If I understand you correctly, you want to check a string to make sure it follows the MM-DD-YYYY pattern?
If so, I would suggest two checks: one to make sure it follows the general pattern of digits, and another to check that the months are first and days are second.
function checkDate( $date )
{
if (preg_match("/[0|1][0-9]/[0-9][1-9]/[0-9]{4}/",$date)
{
if (substr($date,0,2)<=12 && substr($date,3,2)<=31)
{
return true;
}
}
return false
}
Update: Added an additional check on the days to make sure it is valid, based on NullUser's comment
Upvotes: 1
Reputation: 85458
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().
Upvotes: 2
Reputation: 18853
If you are trying to do this to limit user's input, you can always use strtotime() on the users input and convert it to a unix timestamp then use the date() function to display it how you want to.
If you really want to determine if it is in a certain format, or only require a certain format, a preg_match() with a regular expression will be of assistance, I believe on that page they have examples of parsing dates. If not it would be something like this:
if (preg_match('~[0-9]{2}-[0-9]{2}-[0-9]{4}~', $dateStr)) { echo 'Correct format'; }
The obvious flaw with that is the date may pass the format test, but may not be a valid date. In my opinion, accept any date in the user input and use the strtotime / date to get it to the format you want.
Upvotes: 2
Reputation: 3950
you can use regular expressions
if(preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/"))
{
do something
}
Upvotes: 4