Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How format datetime for sql server in laravel?

im trying to format datetime values in laravel to make them match with sql server format, im getting this error:

The separation symbol could not be found Unexpected data found. Unexpected data found. Trailing data

Im using a custom format in my model:

protected $dateFormat = 'd-m-Y H:i:s';

It works good for the create method con controllers, there is no problem, the error happen when try to update and I think is related to how the value is stored in the database.

Using tinker I retrieve the value of updated_at in my model and is shown in the next format:

updated_at: "2018-07-24 09:14:09.000"

So when Im updating this value the format used is:

protected $dateFormat = 'd-m-Y H:i:s';

I think it should be something like d-m-Y H:i:s.000 but doesnt work, how can I solve this?

like image 870
AlexQuezada Avatar asked May 21 '26 02:05

AlexQuezada


1 Answers

I had exactly the same issue, when switching to laravel version 5.6. Now I found the correct way to handle this.

Create a Base class like this and add a public method getDateFormat. There you return the date a little bit different

return 'Y-d-m H:i:s.v';

See that date (d) and month (m) are switched and at the end you need to put a .v which stands for milliseconds. This worked for me fine. See here my complete Base class:

<?php

namespace App\Models\Base;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    public function getDateFormat()
    {
        return 'Y-d-m H:i:s.v';
    }

    public $timestamps  = false;
}
like image 155
dns_nx Avatar answered May 22 '26 16:05

dns_nx