0

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

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

3
Contributors
2
Replies
17
Views
2 Years
Discussion Span
Last Post by cereal
0

I am just guessing here ... but the manual says strtotime returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

So, will FALSE be considered 0? So when the input is 100% $stamp will be set to 0 or -1, both of which are valid as a timestamp (the number of seconds since January 1 1970 00:00:00 UTC). So 100% would be accepted as a date.

0

Hi,

@SalmiSoft sorry I just saw your answer!

@Osagie_1

the problem is given by the regular expression in preg_match(), right now you are checking if there is a digit, not for a specific format, so if the expression matches 1 in 100% it goes through.

strtotime() will return false, so date() will execute like this:

$month = date('m', false);
$day   = date('d', false);
$year  = date('Y', false);

Which will return 01 for $month and $day, 1970 for $year, so checkdate() will be:

checkdate('01', '01', '1970')

Which is regular and will return true.

A better check for dates is this:

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

source: http://php.net/manual/en/function.checkdate.php#113205

Edited by cereal

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.