【发布时间】:2017-02-12 13:50:44
【问题描述】:
我相信,与在浏览器中使用默认格式(即 2016 年 12 月 22 日)的开发者相比,需要使用区域设置日期格式(显示在应用前端)的开发者更多。
所以我在我的 Laravel 项目中为标准日期创建了一个小特征,例如 created_at、updated_at 和 deleted_at:
<?php
namespace App\Traits;
use Carbon\Carbon;
trait FormatDates
{
protected $localFormat = 'd.m.Y H:i';
// save the date in UTC format in DB table
public function setCreatedAtAttribute($date)
{
$this->attributes['created_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getCreatedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getCreatedAtHumanAttribute()
{
return Carbon::parse($this->attributes['created_at'])->diffForHumans();
}
// save the date in UTC format in DB table
public function setUpdatedAtAttribute($date)
{
$this->attributes['updated_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getUpdatedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getUpdatedAtHumanAttribute()
{
return Carbon::parse($this->attributes['updated_at'])->diffForHumans();
}
// save the date in UTC format in DB table
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getPublishedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getPublishedAtHumanAttribute()
{
return Carbon::parse($this->attributes['published_at'])->diffForHumans();
}
// save the date in UTC format in DB table
public function setDeletedAtAttribute($date)
{
$this->attributes['deleted_at'] = Carbon::parse($date);
}
// convert the UTC format to local format
public function getDeletedAtAttribute($date)
{
return Carbon::parse($date)->format($this->localFormat);
}
// get diffForHumans for this attribute
public function getDeletedAtHumanAttribute()
{
return Carbon::parse($this->attributes['deleted_at'])->diffForHumans();
}
}
这些日期实际上只有 3 个函数,这些函数是:
set the date so it can be saved with date time picker
get the date in locale format (22.12.2016 14:39)
get the date in human readable format
所以我的问题是如何使这个特征只有 3 个函数,而不是一直为每个变量重复它?这可行吗?
【问题讨论】: