Convert String to Carbon
Asked Answered
I

4

77

I am using Laravel 5.1

Few days ago I used protected $dates = ['license_expire'] in my model to convert the string date to Carbon instances. In HTML the default value in create form for the date was Carbon\Carbon::now()->format('Y-m-d')

In order to show alert in home page i used <p>Licence Expired: <b>{{ $employee->license_expire < Carbon\Carbon::now()?'License has expired':$employee->license_expire->diffForHumans() }}</b></p>

Till then diffForHumans() method works fine.

But in that case the edit form's default value also was today's date no matter what was in database(I am using a partial form). To resolve it I change the default value in HTML was NUll. And add another method in my model to show current date in create form.

public function getLicenseExpireAttribute($date)
{
    return Carbon::parse($date)->format('Y-m-d');
}

After that when i go to home page i have an FatalErrorException which says Call to a member function diffForHumans() on string

When I check the date with dd($employee->license_expire) it become STRING again.

Can anybody tell me how can I convert the string to Carbon in this situation?

or

Make my create form's default date as today's date, the edit form's date from database and I can use diffForHumans() to show alert in home page?

Illumine answered 13/9, 2015 at 11:34 Comment(0)
C
126

You were almost there.

Remove protected $dates = ['license_expire']

and then change your LicenseExpire accessor to:

public function getLicenseExpireAttribute($date)
{
    return Carbon::parse($date);
}

This way it will return a Carbon instance no matter what. So for your form you would just have $employee->license_expire->format('Y-m-d') (or whatever format is required) and diffForHumans() should work on your home page as well.


If you're using Laravel 9+, you can alternatively use the updated syntax for defining Accessors :

use Illuminate\Database\Eloquent\Casts\Attribute;

public function licenseExpire(): Attribute 
{
    return Attribute::make(
        get: fn ($value) => Carbon::parse($value);
    );
}
Cyler answered 14/9, 2015 at 7:40 Comment(1)
yes! it helped. i did exactly what you said. it works perfectly as i desire.Illumine
E
22

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   
Empale answered 5/3, 2018 at 16:53 Comment(0)
C
0

$filter['dateOfService']='06.2021';

$d1 = Carbon::createFromFormat('m.Y', $filter['dateOfService'], 'Europe/Warsaw')->format('m.Y');
Circus answered 18/6, 2021 at 11:57 Comment(0)
S
-4

Try this

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
Sumption answered 25/5, 2017 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.