Convert the date format of an array to Laravel/PHP

Asked

Viewed 360 times

0

How to convert Indice [date_start] to 2018-08-23 12:19 format with php or Laravel ?

Array
    (
        [id_restaurant] => 303
        [date_start] => 23/08/2018 12:19
        [date_end] => 27/08/2018 12:19
    )

2 answers

1


Yes, if you are bringing this data by a model (which is recommended), you can turn your database field into a Carbon object, added the column name within the array $dates of your model.

Example: $dates = ['date_start','date_end']

That way when you bring that data ($model->find($id)->date_start) it will be an instance of the class Carbon, and with it you use the method format() to play on the date/time model you want.

Example: $model->find($id)->date_start->format('Y-m-d h:i:s')

Reference

  • I am bringing this data via request from a form.

  • In this case, on the controller, give a $date_start = new Carbon($request->all()['date_start']), and the variable date_start will be a Carbon object with the same methods.

  • I did what you told me and gave a print_r to see the return, gave this error, remember that I imported the Carbon class in Controller. Exception: Datetime::__Construct(): Failed to parse time string (23/08/2018 12:19) at position 0 (2): Unexpected Character in file /var/www/html/vendor/Nesbot/Carbon/src/Carbon/Carbon.php on line 547

  • Really, it seems that because it is in the format en can not convert, manipulates the string to get the day, month, year, hours, minutes and seconds. From this you mount a string with the date in the format Y/m/d H:i:s that Carbon can create.

  • You can also use the method createFromDate() where its parameters are: ano (2012), mês (08), dia (24). Example: $data = Carbon::createFromDate(2012,08,24)->format('d-m-Y');

1

On the Laravel I suggest you take a look at Carbon, has enough material there, is part of the mutators that already accompany the Lockable.

or you can set a mutator as well (as long as you are using the Date or Datetime types):

protected $casts = [
    'created_at' => 'datetime:Y-m-d h:i:s',
];

Browser other questions tagged

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