Format date in format

Asked

Viewed 502 times

0

I have that return and I want to convert so as to save the date in the bank YEAR-MES-DIA

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

When I print like this dd($dataOs); Sometimes it comes out the right way 2018-11-02 and sometimes it comes out like this 1970-01-01, only in all the tests I’ve done testing by dd($request->data) the correct date comes seems like it’s something in the conversion I don’t know explain?

  • If the date back 1970-01-01 is why the $request->date is passing something he does not identify as date and hence stick on conversion. tries to print on the screen the $request->data and then the $dataOs and will do the debug of it

  • I already did that and as incredible as it seems from the request a hr print appears the right date but in the $dataOs error 1970-01-01 you know, I did this test to check

  • does so echo $request->data." | ". $dataOs." <hr>";

  • send me the one who appeared

  • $request->data That comes out as a result?

  • Staff found the problem due to the first conversion that used the // converting from - to / I noticed that was the problem when I passed alone - converting from 2018-02-10 to 10-02-2018 resolved believe that somehow the / was giving some conflict

Show 1 more comment

1 answer

-2

Laravel already comes with a library to work with dates, it is very easy to use. Documentation. To convert into the format you need you can work with the Mutators directly into 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 didn’t test the code to see if it’s working, but this is the idea. This way you don’t have to keep treating it in the controller. Suppose you have to integrate via API your application, doing so you don’t have to worry about converting the data field again because it is already ready.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.