How to validate a datetime?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
PhpMachine
Forum Commoner
Posts: 42
Joined: Thu Apr 19, 2007 11:26 am

How to validate a datetime?

Post 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
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post 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.
(#10850)
PhpMachine
Forum Commoner
Posts: 42
Joined: Thu Apr 19, 2007 11:26 am

Post 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...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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
}
PhpMachine
Forum Commoner
Posts: 42
Joined: Thu Apr 19, 2007 11:26 am

Post by PhpMachine »

Thanks Ninja Goat and feyd!

checkdate was exactly what I was looking for.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

Then let me perform a little ninja jig for you...

Image
Post Reply