Brett
Brett

Reputation: 3316

Check if string will convert to date in PHP

An easy follow up From an earlier question ( Date functions in PHP ) I have the following code:

$date_str = "Jan 14th 2011";
$date = new DateTime($date_str);
echo $date->format('d-m-y');

What I am wondering is if there is an easy way to check if $date_str will convert to a date so that I can stop prevent the error when it fails?

Basically I am looking to avoid using try catch statements but perhaps that is not possible.

Upvotes: 4

Views: 6966

Answers (2)

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

Since DateTime class will throw an exception if incorrect values are passed. and the only way you should be dealing with exceptions is by using try catch statement.

try {
    $date = new DateTime($date_str);
    $date->format('d-m-y');
} catch(Exception $e) {
    //$e will contain the caught exception if any.
}

i see no reason for skipping try catch method. if you want to validate the date input then you might want to have a look at php's checkdate function

Upvotes: 1

Marc B
Marc B

Reputation: 360662

As per the docs, the DateTime constructor will throw an exception if the date can't be parsed properly. So...

try {
    $date = new DateTime($date_str);
} catch (Exception $e) {
    die("It puked!");
}

If you're using the procedural interface, you'll get a boolean false instead, so...

$date = date_create_from_format(...);
if ($date === FALSE) {
    die("It puked!");
}

Upvotes: 7

Related Questions