你如何在 PHP 中解析这个日期
how do you parse this date in PHP
我想问一下你是如何解析这个日期的:“12/24/1990”在 laravel 中使用 Carbon 或内置 php 日期方法
$user->profile->birthdate
使用Laravel碳法
$date = "12-24-1990";
$carbon_date = Carbon\Carbon::createFromFormat('m/d/Y', $date);
使用PHP方法
$newdate = date('m/d/Y',strtotime($date));
两种解决方案都适用于 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
强制转换为 Profile
模型中的一个 Carbon
对象,然后您可以使用以下代码根据需要设置格式:
/**
* 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
您可以像@Jesper 所说的那样使用 date mutators like this in your Profile
model (or 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');
就这样做
use Carbon\Carbon;
Carbon::parse($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));
希望对您有所帮助。
我想问一下你是如何解析这个日期的:“12/24/1990”在 laravel 中使用 Carbon 或内置 php 日期方法
$user->profile->birthdate
使用Laravel碳法
$date = "12-24-1990";
$carbon_date = Carbon\Carbon::createFromFormat('m/d/Y', $date);
使用PHP方法
$newdate = date('m/d/Y',strtotime($date));
两种解决方案都适用于 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
强制转换为 Profile
模型中的一个 Carbon
对象,然后您可以使用以下代码根据需要设置格式:
/**
* 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
您可以像@Jesper 所说的那样使用 date mutators like this in your Profile
model (or 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');
就这样做
use Carbon\Carbon;
Carbon::parse($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));
希望对您有所帮助。