使用受保护的$ date格式化日期laravel

时间:2015-11-27 20:45:59

标签: php mysql date laravel

我做了一些搜索,以便格式化我视图上显示的日期。我发现如果将字段插入到模型下的受保护的$ dates数组中,我可以根据需要操作日期。但是现在当我想在数据库中进行新的插入时,我得到了

Unexpected Date Format

以下是我模特中的内容:

protected $fillable = ['name', 'description', 'address','caption', 'video', 'visibility', 'image', 'publish_at', 'link'];

protected $dates = ['publish_at'];

在我看来:

    <p class = "day">
        {{$event->publish_at->format('d')}}
    </p>


    <p class = "month">
        {{$event->publish_at->format('M')}}
    </p>

我尝试在保存之前再次格式化日期:

$date = new ElephantCalender(array(
        'name' => $request->get('name'),
        'description'  => $request->get('description'),
        'caption'  => $request->get('caption'),
        'address'  => $request->get('address'),
        'link'  => $request->get('link'),
        'visibility'  => $request->get('visibility'),
        'publish_at'  => $request->get('publish_at')->format('yyyy-mm-dd')
    ));

    $date->save();

这告诉我,我不能在字符串上使用format()。有没有其他方法可以将日期设置为正确的格式提交到表格中?

2 个答案:

答案 0 :(得分:1)

Eloquent使用Carbon创建日期对象。它还可以使用Carbon根据配置的日期格式将日期对象存储到数据库中。

这应该有效:

'publish_at' => new Carbon($request->get('publish_at'))

输入格式非常重要。像这样,你让Carbon或PHP决定如何解析输入日期字符串。有些日期格式含糊不清:2015年7月11日可能意味着7月11日或11月7日。绝对确定,您可以使用DateTime::createFromFormat,如@volkinc建议的那样。在任何一种情况下,结果对象都将由Eloquent格式化。

答案 1 :(得分:0)

我不确定从get(..)

格式化日期

使用

$tempT = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

或类似

$d = new DateTime('10-16-2003');

$timestamp = $d->getTimestamp(); // Unix timestamp
$tempT = $d->format('Y-m-d'); // 2003-10-16

因为你可以在查询中使用$ tempT

相关问题