Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_date() is malfunctioning

Tags:

date

regex

php

i have a php methode that checks if a passed in parameter is a date. Here's it:

public function is_Date($str){ 
        if (is_numeric($str) ||  preg_match('^[0-9]^', $str)){  
            $stamp = strtotime($str);
            $month = date( 'm', $stamp ); 
            $day   = date( 'd', $stamp ); 
            $year  = date( 'Y', $stamp ); 
            return checkdate($month, $day, $year); 
        } 
        return false; 
}

then, i test-drove it like this:

$var = "100%";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
} 

$var = "31/03/1970";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
}

$var = "31/03/2005";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
}

$var = "31/03/1985";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
}

Note that each of the ifs also has an else statement as in :

else{
   echo $var.' '.'is not a date' 
}

OUTPUT:

100% is a Date
31/03/1970 is a Date
31/03/2005 is a Date
31/03/1985 is a Date

My problem is, why is 100% displaying as a date and why is 31/03/1985 not being read as a date ?

Any clue as to why will be highly appreciated as i am not too expertise in Regex

like image 453
Osagie Odigie Avatar asked Dec 20 '14 06:12

Osagie Odigie


2 Answers

You are using ^ at end of regex string, Meaning of ^ is to compare beginning of string.

Also, as hjpotter92 suggested, you could simply use is_numeric(strtotime($str))

Your function should look like:

public function is_Date($str){ 
    $str=str_replace('/', '-', $str);  //see explanation below for this replacement
    return is_numeric(strtotime($str)));
}

Documentation says:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

like image 67
Ravi Dhoriya ツ Avatar answered Sep 27 '22 23:09

Ravi Dhoriya ツ


I'd got it working now! the new output has stopped displaying 100% as a date, which was what I planned. Here's the final code snippet that does the job

public function is_Date($str){ 
    $str = str_replace('/', '-', $str);     
    $stamp = strtotime($str);
    if (is_numeric($stamp)){  
       $month = date( 'm', $stamp ); 
       $day   = date( 'd', $stamp ); 
       $year  = date( 'Y', $stamp ); 
       return checkdate($month, $day, $year); 
    }  
    return false; 
}
echo "A million thanks to you all ! you guys are the best !";
like image 22
Osagie Odigie Avatar answered Sep 28 '22 00:09

Osagie Odigie