Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime::__construct(): Failed to parse time string (16/07/2020) at position 0 (1): Unexpected character

Tags:

laravel

In my Laravel 5.8 application, I have:

config/app.php

'date_format' => 'd/m/Y',
'date_format_js' => 'dd/mm/yy',

Model

use Carbon\Carbon;

class HrHolidayDate extends Model
{
    protected $table = 'hr_holiday_dates';

    protected $fillable = [
        'holiday_name',
        'holiday_date',

    ];

    protected $dates = [
        'holiday_date'
    ];


    protected $casts = [];


    public function setHolidayDateAttribute($input)
    {
        $this->attributes['holiday_date'] =
            Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
    }


    public function getHolidayDateAttribute($input)
    {
        return Carbon::createFromFormat('Y-m-d', $input)
            ->format(config('app.date_format'));
    }
}

I tried to format it in the Blae view as shown below:

view

@foreach($holidays as $key => $holiday)
    <td>
        {{Carbon\Carbon::parse($holiday->holiday_date)->format('d-m-Y') ?? '' }}
    </td>
@endforeach

When I wanted to render the view blade, I got this error:

[2020-07-15 11:57:56] production.ERROR: DateTime::__construct(): Failed to parse time string (16/07/2020) at position 0 (1): Unexpected character (View: C:\xampp\htdocs\laravelapp\resources\views\hr\holiday_dates\index.blade.php) {"userId":466,"exception":"[object] (ErrorException(code: 0): DateTime::__construct(): Failed to parse time string (16/07/2020) at position 0 (1): Unexpected character (View: C:\xampp\htdocs\laravelapp
esources\views\hr\holiday_dates\index.blade.php) at C:\xampp\htdocs\laravelapp\vendor
esbot\carbon\src\Carbon\Traits\Creator.php:81, Exception(code: 0): DateTime::__construct(): Failed to parse time string (16/07/2020) at position 0 (1): Unexpected character at C:\xampp\htdocs\laravelapp\vendor
esbot\carbon\src\Carbon\Traits\Creator.php:81) [stacktrace]

How do I resolve it?

Thanks

like image 576
mikefolu Avatar asked Jul 15 '20 11:07

mikefolu


1 Answers

Because Carbon does not understand d/m/Y format out of the box. If you use slashes it should be mm/dd/yyyy in that case. d/m/Y is not an official date format.

You can use :

{{ Carbon\Carbon::createFromFormat('d/m/Y', $holiday->holiday_date)->format('d-m-Y') }}
like image 100
sta Avatar answered Nov 15 '22 02:11

sta