Reputation: 767
I have small laravel project working on date conversion. I have date string that getting from request on format dd/mm/yyyy. Code and result show as below.
$request->stockupdate ;
// dd/mm/yyyy (02/05/2019)
Then I try to convert to yyyy-mm-dd using carbon.
$_stockupdate= Carbon::parse($request->stockupdate)->format('Y-m-d');
I got parse result as below.
2019/02/05 // Seem it is 2 Feb 2019 not 5 May 2019.
That's wrong, It should be 2019/05/02 instead. Any advise or guidance would be greatly appreciated, Thanks.
Upvotes: 9
Views: 61313
Reputation: 148
This may be also nice and clean
// DD Day (2 Numbers)
// MM Month (2 Numbers)
// YYYY Year (4 Numbers)
// Will format to 2021-03-18
Carbon\Carbon::now()->isoFormat('YYYY-MM-DD');
If you use a Model like $data->expired_at
you need to set the type as a date
add this into your Model File:
/**
* The attributes that should be date.
*
* @var array
*/
protected $dates = [
'expired_at',
];
Upvotes: 4
Reputation: 1814
You can try this :
$date = str_replace('/', '-', $request->stockupdate);
$newDate = date("Y-m-d", strtotime($date));
OR
Carbon::createFromFormat('d/m/Y', $request->stockupdate)->format('Y-m-d')
Upvotes: 3
Reputation: 14318
You can try this:
Carbon::createFromFormat('d/m/Y', $request->stockupdate)->format('Y-m-d')
Upvotes: 40