RobFos
RobFos

Reputation: 961

strtotime date validation passes on invalid date

I am in the middle of setting up a basic CMS that allows the client to add articles to their mobile app. The CMS is coded in PHP and will use JSON to deliver the content to the mobile app.

Now my problem is there is an option to publish the article at a certain date, so I want to validate the date to check it is valid.

So to test possibilites I made a small script. I am using strtotime() to check the date is valid, my script is:

<?php

    $date[] = '2011-31-01';
    $date[] = '2011-02-31';

    foreach($date as $str) {
        if(strtotime($str) == false) {
            $result[] = '<p>[' . $str . '] Resulted in an <span style="color: red;">Error.</span></p>';
        } else {
            $result[] = '<p>[' . $str . '] Resulted in <span style="color: green;">Success.</span></p>';
        }
    }

    foreach($result as $return) {
        echo $return;
    }

?>

Now my problem is the date 2011-02-31 which is 31st February 2011 is returning as valid, when obviously it isn't. So my question is why does it do this? and is there a better method to check that the date is valid and exists?

Thanks in advance.

Upvotes: 1

Views: 3357

Answers (2)

poke
poke

Reputation: 387993

Unless you have one (or a small set) fixed format for your date string it will be hard to get an acceptable result. In case you know the format, you can either parse the string directly yourself (and test it afterwards with checkdate), or you use strptime to try parsing against known formats until you get a valid result.

If you don’t know the format, and you have to use strtotime, then you are required to accept that strtotime will try parsing the date string in the best possible way. This may lead to different dates than it was expected to be.

Upvotes: 2

Mob
Mob

Reputation: 11106

checkdate(); Validates a Gregorian date. Returns TRUE if the date given is valid; otherwise returns FALSE.

 if(checkdate(2, 31, 2011)){
      echo "Yeah";

  } else {echo "nah";}

It returns false!

That's the way to go.

Upvotes: 6

Related Questions