Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FutureWeb's avatar

Carbon Parse() UK date time format dd/mm/yyyy

Hi Lara Folks I am having some trouble importing UK dates using Carbon Parse:

Could not parse '25/02/2021 20:34:00': DateTime::__construct(): Failed to parse time string (25/02/2021 20:34:00) at position 0 (2): Unexpected character

Mode looks like:


use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Promotion extends Model
{
    use HasFactory;

    protected $guarded = [];
    protected $casts = ['promotion_starts' => 'start_date','promotion_ends'=>'end_date','date_added'=>'added_date'];
    protected $appends = ['start_date_for_editing','end_date_for_editing','added_date_for_editing'];
    

    public function getStartDateForEditingAttribute()
    {
        return $this->start_date->format('d/m/Y');
    }

    public function setStartDateForEditingAttribute($value)
    {

        $this->start_date = Carbon::parse($value);
    }

    public function getEndDateForEditingAttribute()
    {
        return $this->end_date->format('d/m/Y');
    }

    public function setEndDateForEditingAttribute($value)
    {
        $this->end_date = Carbon::parse($value);
    }

    public function getAddedDateForEditingAttribute()
    {
        return $this->added_date->format('d/m/Y');
    }

    public function setAddedDateForEditingAttribute($value)
    {

        $this->added_date = Carbon::parse($value);
    }
}```
0 likes
6 replies
MichalOravec's avatar

Use createFromFormat

public function setStartDateForEditingAttribute($value)
{
    $this->attributes['start_date'] = Carbon::createFromFormat('d/m/Y H:i:s', $value)->toDateTimeString();
}
2 likes
Snapey's avatar
Snapey
Best Answer
Level 122

use createFromFormat?

Carbon::createFromFormat('d/m/Y H:i:s', $value)
1 like
FutureWeb's avatar

I did try createFromFormat but it returns:

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

Snapey's avatar

carefully examine the format you are being passed

is it two or four digit year ?

FutureWeb's avatar

HaHa turned out it was the livewire component I used now() to set a default switched it for date('d/m/Y H:i:s') and sorted the second error :)

Thanks for all your help

Please or to participate in this conversation.