如何从刀片数据库视图中的created_at或updated_at字段在刀片视图中显示unix时间戳?

时间:2019-03-28 13:05:33

标签: laravel datetime laravel-5 eloquent unix-timestamp

我想从laravel 5.8中的数据库字段(created_at和updated_at)中获取UNIX时间戳或将created_at或updated_at日期转换为UNIX时间戳格式,我该怎么做?

这是我在控制器中的代码:

public function viewArchives(){
$data = Archive::select(‘created_at’)->get();
return view(‘view.archives’, compact(‘data’));
}

并在view / archives.blade.php中:

<?php echo $data;?>

结果是:

{“created_at”:”2019-03-17 19:10:30″}

但我希望结果是这样的:

{“created_at”:”1552849830″}

如何获得此结果?

3 个答案:

答案 0 :(得分:1)

$string = '2019-03-17 19:10:30';

$obj = new stdClass;
$obj->created_at = $string;

$collection = [$obj];

foreach ($collection as $k => &$v) {
    $collection[$k]->created_at = strtotime($v->created_at);
}

//var_dump($collection);

$string = '2019-03-17 19:10:30';

$obj = new stdClass;
$obj->created_at = $string;

$collection = [$obj];

array_walk($collection, function (&$item, $key) {
    $item->created_at = strtotime($item->created_at);
});

//var_dump($collection);

或者您的情况

    public function viewArchives()
    {
        $data = Archive::select('created_at')->get();
        foreach ($data as $k => &$v) {
            $v->created_at = strtotime($v->created_at);
        }
        return view('view.archives', compact('data'));
    }

    public function viewArchives()
    {
        $data = Archive::select('created_at')->get();
        array_walk($data, function (&$item, $key) {
            $item->created_at = strtotime($item->created_at);
        });
        return view('view.archives', compact('data'));
    }

这是使用array_walk()函数的好地方。

答案 1 :(得分:0)

添加strtotime()view / archives.blade.php:

<?php echo strtotime( $data );?>

答案 2 :(得分:0)

使用雄辩的Model实际上可以定义每列$casts

class SomeModel extends Model
{

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'created_at' => 'datetime'
    ];
}

如果要改用纪元时间戳,只需删除此转换(可能存在)。


当时间戳不是来自任何雄辩的Model时,仍然可以使用Blade渲染:

@php
$dt = new DateTime();
echo $dt->setTimestamp( $timestamp )->format("Y-m-d H:m:s");
@endphp

反之亦然:

@php
echo strtotime( $isodate );
@endphp