Carbon (laravel) deal with invalid date

Nemo Grippa picture Nemo Grippa · Oct 19, 2017 · Viewed 20.5k times · Source

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';

Answer

Tudor picture Tudor · Oct 19, 2017

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';
}