我在数据库上有一些时间戳记录,在时间戳上有尾随毫秒,有些没有。如何允许碳中的尾随数据(毫秒)?这可能吗?
这是我的数据示例
我不能总是手动更改数据,因为还有一些其他服务使用相同的数据库,有时会存储带有尾随毫秒的时间戳。
最佳答案
当您使用时 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/