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

问题描述 投票:5回答:2

我想从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″}

怎么能得到这个结果?

laravel datetime laravel-5 eloquent unix-timestamp
2个回答
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()功能的好地方。


0
投票

添加strtotime()视图/ archives.blade.php:

<?php echo strtotime( $data );?>
© www.soinside.com 2019 - 2024. All rights reserved.