Nemo Grippa
Nemo Grippa

Reputation: 469

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

Upvotes: 0

Views: 3333

Answers (3)

Kenneth
Kenneth

Reputation: 2993

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).

Upvotes: 2

ChrisBratherton
ChrisBratherton

Reputation: 1590

As LorenzoBerti mentioned you can use carbon to parse your date:

$birthday = Carbon::parse($birthday)->format('d.m.y');

Notice the format() method, this should give you the format that you need.

Upvotes: 0

LorenzoBerti
LorenzoBerti

Reputation: 6974

For manage Laravel date you can use a beautiful package named Carbon that resolve your problem with Carbon::parse("data");

here you can fine documentation.

http://carbon.nesbot.com/docs/ And here the api documentation for Laravel:

https://laravel.com/api/5.5/Illuminate/Support/Carbon.html

Upvotes: 0

Related Questions