How to convert date format from dd/mm/yyyy to yyyy-mm-dd using carbon on Laravel
Asked Answered
B

3

9

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.

Bentwood answered 2/5, 2019 at 10:42 Comment(2)
This happend if you modifiy the attribute in model file. i think you had already written a code in model to change the format and here you again try to format the same attribute. You also try coding $_stockupdate= Carbon::parse($request->getOriginal('stockupdate'))->format('Y-m-d');Thousandth
Dear Prashant Prajapati , thanks.Bentwood
R
37

You can try this:

Carbon::createFromFormat('d/m/Y', $request->stockupdate)->format('Y-m-d')
Ronn answered 2/5, 2019 at 10:47 Comment(1)
Dear nakov, This is exactly I want, Thank you very much.Bentwood
P
4

This may be also nice and clean

Carbon Live Editor


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


Using with a Model

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',
    ];
Prurigo answered 17/3, 2021 at 23:44 Comment(0)
F
3

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')
Franck answered 2/5, 2019 at 10:52 Comment(1)
Dear jithesh jose, Thank you.Bentwood

© 2022 - 2024 — McMap. All rights reserved.