I have a quite simple problem.. I use the Carbon::parse($date)
function with $date = '15.15.2015'
. Of course it can not return a valid string because there is no 15th month. But how can i "ignore" the error message?
Great would be something like
if (Carbon::parse($date) != error) Carbon::parse($date);
else echo 'invalid date, enduser understands the error message';
You can catch the exception raised by Carbon like this:
try {
Carbon::parse($date);
} catch (\Exception $e) {
echo 'invalid date, enduser understands the error message';
}
Later edit: Starting with Carbon version 2.34.0, which was released on May 13, 2020, a new type of exception is being thrown: Carbon\Exceptions\InvalidFormatException
So if you're using a newer version of Carbon, you can actually do this more elegantly
try {
Carbon::parse($date);
} catch (\Carbon\Exceptions\InvalidFormatException $e) {
echo 'invalid date, enduser understands the error message';
}
Thank you Christhofer Natalius for pointing this out!
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