Laravel Carbon 允许在 Postgresql 时间戳中使用尾随数据

标签 laravel postgresql timestamp php-carbon

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

这是我的数据示例

timestamp data sometimes have trailing millisecond

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

最佳答案

当您使用时 Postgres ,你的时间戳可能有 TIME WITH TIMEZONE
示例: "2018-04-19 07:01:19.929554" .

在这种情况下,必须向您的模型添加日期 Mutator。

在您的模型中为日期修改器添加此字段:

protected $dateFormat = 'Y-m-d H:i:sO';

替代解决方案:

由于您混合了带毫秒和不带毫秒的时间戳,我建议您使用 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')
    }
}

关于Laravel Carbon 允许在 Postgresql 时间戳中使用尾随数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59496052/

相关文章:

json - PostgreSQL 在 JSON 数组中搜索值

php - 如何使用php在postgresql表中插入timestampz值

sql - 如何使用 TIMESTAMP 数据类型减少 Oracle (SQL Plus) 中的列宽?

Java - SimpleDateFormat 格式化程序以毫秒为单位返回纪元时间

laravel - Maatwebsite Excel加载功能不起作用

javascript - 如何使用innerHTML在Laravel中打印数组

php - 在 Laravel 5.1 中使用 .env 设置存储路径

php - sync or updateExistingPivot with Laravel——如何根据第三个标准进行填充

postgresql - 如何根据条件分离和计算一列?

hadoop - hive 将字符串转换为时间戳会丢弃毫秒信息