[我想问一下您如何将这个日期解析为:“ 12/24/1990”,在Laravel中使用Carbon或内置于php日期方法中
$user->profile->birthdate
只需这样做
use Carbon\Carbon;
Carbon::parse($user->profile->birthdate)->format('m/d/Y')
您可以在date mutators模型中使用这样的Profile
(或@Jesper所说的date casting:]
class Profile extends Model
{
protected $dates = [
'birthdate', // date fields that should be Carbon instance
];
}
因此,无论何时检索模型,Laravel
都会自动将birthdate
属性强制转换为Carbon
实例,并且您可以使用format
方法对其进行格式化,例如:
$user->profile->birthdate->format('m/d/y');
使用laravel Carbon,您可以像下面一样解析日期
$carbonToday = Carbon::now();
$date = $carbonToday->format('m/d/Y');
使用PHP方法
$carbonToday = Carbon::now();
$date = date('m/d/Y',strtotime($carbonToday));
希望这会对您有所帮助。
这两种解决方案均适用于Laravel 5. *和6。*。
第一个解决方案
您可以通过将以下内容放入birthdate
模型中,将Profile
变量始终转换为所需的格式。
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'birthdate' => 'datetime:m/d/Y',
];
参考:https://laravel.com/docs/6.x/eloquent-mutators#date-casting
第二解决方案:
您还可以将birthdate
强制转换为Carbon
模型中的Profile
对象,然后可以使用以下代码根据需要对其进行格式化:
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'birthdate',
];
然后您始终可以执行以下操作以不同方式设置其格式:
$user->profile->birthdate->format('m/d/Y')
参考:https://laravel.com/docs/6.x/eloquent-mutators#date-mutators
使用Laravel碳法
$date = "12-24-1990";
$carbon_date = Carbon\Carbon::createFromFormat('m/d/Y', $date);
使用PHP方法
$newdate = date('m/d/Y',strtotime($date));