Search code examples
phplaravelstrtotimephp-carbon

Laravel use special date format


Right now i use the strtotime function to convert german date format (01.01.2017) to the stock (2017-01-01). For example i use date('Y-m-d', strtotime($birthday)). Now i want to use the short german date format and convert it to stock. E.g. 1.1.17 should be converted to 2017-01-01. How can i do this? Using the strtotime function doesn't work (or I am to silly to use it right)

And another question: How can i catch the error if somebody types in 32.01.2017? I only get a debug notification or, on production, a "Whoops, ..." "error" messsage. Would be great to make some sweet alert message instead. I get following error message:

DateTime::__construct(): Failed to parse time string (32.10.2016) at position 0 (3): Unexpected character


Solution

  • You can use this one.

    $date = '1.1.17';
    $year = substr($date, -2);
    $finalDate= substr($date, 0, -2)."20".$year;
    Carbon::createFromFormat('m.d.Y',$finalDate)->format('Y-m-d');
    

    (updated).