joenpc npcsolution
joenpc npcsolution

Reputation: 767

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

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

Answers (3)

Daniel Juric
Daniel Juric

Reputation: 148

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',
    ];

Upvotes: 4

Jithesh Jose
Jithesh Jose

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

nakov
nakov

Reputation: 14318

You can try this:

Carbon::createFromFormat('d/m/Y', $request->stockupdate)->format('Y-m-d')

Upvotes: 40

Related Questions