我在数据库上有一些时间戳记录,在时间戳上有尾随毫秒,而有些则没有。如何允许拖尾数据(毫秒)以碳的形式存在?这个是可能的吗?
这是我的数据示例

我不能总是手动更改数据,因为还有一些其他服务使用相同的数据库,有时会以毫秒为单位存储时间戳。
发布于 2020-01-07 14:06:51
由于您正在使用Postgres,因此您的时间戳可能包含TIME WITH TIMEZONE
示例: "2018-04-19 07:01:19.929554"。
在这种情况下,必须将日期赋值函数添加到模型中。
在您的模型中为添加以下字段:
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')
}
}发布于 2020-01-10 17:12:41
我在Laravel中观察到,在数据库中存储日期时间忽略了毫秒字段,这可能取决于版本和数据库服务器类型。
另外,Laravel有whereData()和whereTime()查询构建器,但是我们在所有情况下都需要类似whereDateTimeTz()的查询构建器。
我建议将datetime作为unix timestamps存储在数据库中。
从用户时区转换为GMT,并将其作为millis-timestamp保存到数据库中
Carbon::parse('date', 'user_timezone')->setTimezone('GMT')->getPreciseTimestamp(3);在显示时,只需将数据库时间戳(GMT)转换回用户时区,包括DST状态。
发布于 2020-03-12 20:48:41
如果从数据库接收的时间戳与预期的$dateFormat不匹配,则Laravel 7通过回退到Carbon::parse来提供更好的日期解析。
https://stackoverflow.com/questions/59496052
复制相似问题