Format date in laravel

0

I have this return and I want to convert to save the date in the YEAR - MES - DAY

$dataOs = date('Y-m-d', strtotime($request->data));

When I print like dd($dataOs); sometimes it goes out the right way 2018-11-02 and sometimes it goes like this 1970-01-01 , but in all tests that I performed by testing for dd($request->data) the date comes correct does it seem like it is something in the conversion I do not know how to explain?

    
asked by anonymous 23.11.2018 / 19:15

1 answer

0

Laravel already comes with a library to work with dates, it is very easy to use. Documentation. To convert to the format you need you can work with Mutators directly in your model, would look something like this:

 function setDataAttribute($value){
       $dia = substr($value, 8, 2);
       $mes = substr($value, 5, 2);
       $ano = substr($value, 0, 4);

       this->attributes['data'] = Carbon::create($ano, $mes, $dia, 0, 0);

   }

Note: I did not test the code to see if it works, but the idea is this. This way you do not have to deal with this in the controller. Suppose you have to integrate your application via API, so you do not have to worry about converting the date field again because it's ready.

    
26.11.2018 / 17:54