Laravel 8 - SQL Server Date Type (Not Datetime) Parsing Error

Viewed 127

I want to format date where I get from SQL Server where data type is date (not datetime).

I have tried add date casting in model like this:

class MyModel extends Model
{
    protected $casts = [
        'date' => 'date:Y',
    ];
}

but there is an error:

Could not parse 'Apr 20 2021 12:00:00:AM': DateTime::__construct(): Failed to parse time string (Apr 20 2021 12:00:00:AM) at position 20 (:)

When I change data type in SQL Server to datetime, there was worked perfectly.

I have tried any parsing method (in accessor) use Carbon or date('d-m-Y', strtotime($date)), there still error when data type is date but working well when data type is datetime.

Any suggestions? Thanks.

1 Answers

So I create an accessor to manipulate the date string and than format it.

public function getDateAttribute($date)
{
    $date = explode(' ', $date);
    return date('Y', strtotime($date[1].$date[0].$date[2]));
}
Related