Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
Brett Avatar asked Jan 16 '23 15:01

Brett


1 Answers

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!");
}
like image 86
Marc B Avatar answered Jan 20 '23 16:01

Marc B