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.
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!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With