Page 1 of 1

How to validate a datetime?

Posted: Tue Apr 24, 2007 12:04 pm
by PhpMachine
Hi folks
I have problems validating time...

How do you validate for instance 2007-02-35?
That should be false.

2007-02-29 should be false too, etc.

I've tried:

Code: Select all

strtotime("2007-02-29")
and it says its a correct date.

It seems that strtotime accepts all days 00-31 for every month.
How come?

Greetings

Posted: Tue Apr 24, 2007 12:43 pm
by Christopher
Spit the date into the three values and do checks starting with the year (checking for leap year) and then month (1-12) and then day within the correct range based on the year and month.

Posted: Tue Apr 24, 2007 12:45 pm
by PhpMachine
Yes, of course I could do that ;)

But isn't there built-in support for this?
I don't see why strtotime actually says that "2007-02-30" is valid...

Posted: Tue Apr 24, 2007 3:16 pm
by feyd
Because it's converted to a valid value.

Code: Select all

[feyd@home]>php -r "echo date('Y-m-d', strtotime('2007-02-30'));"
2007-03-02

Posted: Tue Apr 24, 2007 3:34 pm
by Luke

Code: Select all

$date = '2007-02-35';
list($year,$month,$day) = explode("-", $date);
if (checkdate($month, $day, $year))
{
    // valid date
}
else
{
    // pork and beans
}

Posted: Tue Apr 24, 2007 6:02 pm
by PhpMachine
Thanks Ninja Goat and feyd!

checkdate was exactly what I was looking for.

Posted: Tue Apr 24, 2007 6:07 pm
by Luke
Then let me perform a little ninja jig for you...

Image