Laravel Carbon 允许在 Postgresql 时间戳上跟踪数据

den*_*gas 6 postgresql timestamp laravel php-carbon

我在数据库上有一些时间戳记录,它们的时间戳有尾随毫秒,而有些则没有。如何允许碳中的尾随数据(毫秒)?这可能吗?

这是我的数据示例

时间戳数据有时有尾随毫秒

我不能总是手动更改数据,因为还有一些其他服务使用相同的数据库,有时会存储带有尾随毫秒的时间戳。

Sap*_*aik 2

当您使用时Postgres,您的时间戳可能有TIME WITH TIMEZONE

例子: "2018-04-19 07:01:19.929554"

在这种情况下,必须向您的模型添加一个日期突变器。

在您的模型中添加此字段作为日期变换器:

protected $dateFormat = 'Y-m-d H:i:sO';
Run Code Online (Sandbox Code Playgroud)

替代解决方案:

由于您混合了带毫秒和不带毫秒的时间戳,我建议您使用 Laravel 字段变异器尝试此解决方案:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Parse the created at field which can optionally have a millisecond data.
     *
     * @param  string  $created_at
     * @return Carbon::Object
     */
    public function getCreatedAtAttribute($created_at)
    {
            // Try to remove substring after last dot(.), removes milliseconds
            $temp = explode('.', $created_at);

            // If created_at had milliseconds the array count would be 2
            if(count($temp) == 2) {
                unset($temp[count($temp) - 1]); // remove the millisecond part
            } else {
                $temp = [$created_at]; // created_at didnt have milliseconds set it back to original
            }

            return Carbon::parse(implode('.', $temp))->format('Y-m-d H:i:s')
    }
}
Run Code Online (Sandbox Code Playgroud)