将字符串转换为碳
Convert String to Carbon
我正在使用Laravel 5.1
几天前,我在模型中使用 protected $dates = ['license_expire']
将字符串日期转换为 Carbon 实例。在 HTML 中,创建表单中日期的默认值为 Carbon\Carbon::now()->format('Y-m-d')
为了在主页上显示提醒,我使用了<p>Licence Expired: <b>{{ $employee->license_expire < Carbon\Carbon::now()?'License has expired':$employee->license_expire->diffForHumans() }}</b></p>
到那时 diffForHumans() 方法工作正常。
但在那种情况下,无论数据库中有什么内容,编辑表单的默认值也是今天的日期(我使用的是部分表单)。为了解决它,我将 HTML 中的默认值更改为 NUll。并在我的模型中添加另一种方法以在创建表单中显示当前日期。
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date)->format('Y-m-d');
}
在那之后,当我进入主页时,我有一个 FatalErrorException
上面写着 Call to a member function diffForHumans() on string
当我用 dd($employee->license_expire)
检查日期时,它又变成了 STRING。
谁能告诉我在这种情况下如何将字符串转换为 Carbon?
或
将我的创建表单的默认日期设置为今天的日期,将编辑表单的日期设置为来自数据库的日期,然后我可以使用 diffForHumans() 在主页中显示警报吗?
你快到了。
删除protected $dates = ['license_expire']
然后将您的 LicenseExpire
访问器更改为:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
这样无论如何都会 return 一个 Carbon
实例。
因此,对于您的表单,您只需要 $employee->license_expire->format('Y-m-d')
(或任何需要的格式)并且 diffForHumans()
也应该在您的主页上工作。
希望对您有所帮助!
试试这个
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
为什么不尝试使用以下方法:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
$filter['dateOfService']='06.2021';
$d1 = Carbon::createFromFormat('m.Y', $filter['dateOfService'], 'Europe/Warsaw')->format('m.Y');
我正在使用Laravel 5.1
几天前,我在模型中使用 protected $dates = ['license_expire']
将字符串日期转换为 Carbon 实例。在 HTML 中,创建表单中日期的默认值为 Carbon\Carbon::now()->format('Y-m-d')
为了在主页上显示提醒,我使用了<p>Licence Expired: <b>{{ $employee->license_expire < Carbon\Carbon::now()?'License has expired':$employee->license_expire->diffForHumans() }}</b></p>
到那时 diffForHumans() 方法工作正常。
但在那种情况下,无论数据库中有什么内容,编辑表单的默认值也是今天的日期(我使用的是部分表单)。为了解决它,我将 HTML 中的默认值更改为 NUll。并在我的模型中添加另一种方法以在创建表单中显示当前日期。
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date)->format('Y-m-d');
}
在那之后,当我进入主页时,我有一个 FatalErrorException
上面写着 Call to a member function diffForHumans() on string
当我用 dd($employee->license_expire)
检查日期时,它又变成了 STRING。
谁能告诉我在这种情况下如何将字符串转换为 Carbon?
或
将我的创建表单的默认日期设置为今天的日期,将编辑表单的日期设置为来自数据库的日期,然后我可以使用 diffForHumans() 在主页中显示警报吗?
你快到了。
删除protected $dates = ['license_expire']
然后将您的 LicenseExpire
访问器更改为:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
这样无论如何都会 return 一个 Carbon
实例。
因此,对于您的表单,您只需要 $employee->license_expire->format('Y-m-d')
(或任何需要的格式)并且 diffForHumans()
也应该在您的主页上工作。
希望对您有所帮助!
试试这个
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
为什么不尝试使用以下方法:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
$filter['dateOfService']='06.2021';
$d1 = Carbon::createFromFormat('m.Y', $filter['dateOfService'], 'Europe/Warsaw')->format('m.Y');