您如何用PHP解析此日期

问题描述 投票:-1回答:5

[我想问一下您如何将这个日期解析为:“ 12/24/1990”,在Laravel中使用Carbon或内置于php日期方法中

$user->profile->birthdate
php laravel php-carbon
5个回答
2
投票

只需这样做

use Carbon\Carbon;
Carbon::parse($user->profile->birthdate)->format('m/d/Y')

2
投票

您可以在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');

0
投票

使用laravel Carbon,您可以像下面一样解析日期

        $carbonToday = Carbon::now();
        $date = $carbonToday->format('m/d/Y');

使用PHP方法

       $carbonToday = Carbon::now();
       $date = date('m/d/Y',strtotime($carbonToday));

希望这会对您有所帮助。


0
投票

这两种解决方案均适用于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


-1
投票

使用Laravel碳法

$date = "12-24-1990";
$carbon_date = Carbon\Carbon::createFromFormat('m/d/Y', $date);

使用PHP方法

 $newdate = date('m/d/Y',strtotime($date));
© www.soinside.com 2019 - 2024. All rights reserved.