Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carbon (laravel) deal with invalid date

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';
like image 359
Nemo Grippa Avatar asked Oct 19 '17 11:10

Nemo Grippa


1 Answers

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!

like image 186
Tudor Avatar answered Sep 19 '22 02:09

Tudor