Laravel 时间戳将时间保存为 unix 时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35915576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:22:42  来源:igfitidea点击:

Laravel timestamp saving time as unix timestamp

laravel

提问by Marco

I was wondering what would be the easiest way to change in laravel to save timestamps in database as unix valid timestamp?

我想知道在 laravel 中更改以将数据库中的时间戳保存为 unix 有效时间戳的最简单方法是什么?

Thanks in advance!

提前致谢!

回答by Alexey Mezenin

Please read about Laravel date mutators: https://laravel.com/docs/5.1/eloquent-mutators#date-mutators

请阅读 Laravel 日期修改器:https://laravel.com/docs/5.1/eloquent-mutators#date-mutators

By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON

默认情况下,时间戳的格式为“Ymd H:i:s”。如果您需要自定义时间戳格式,请在模型上设置 $dateFormat 属性。此属性确定日期属性在数据库中的存储方式,以及模型序列化为数组或 JSON 时的格式

Also, you can override getDateFormat():

此外,您可以覆盖getDateFormat()

protected function getDateFormat()
{
    return 'U';
}

And use this in your migration files:

并在您的迁移文件中使用它:

$table->integer('updated_at');
$table->integer('created_at');

And, if you use soft deletes:

而且,如果您使用软删除:

$table->integer('deleted_at');

https://laravel.com/docs/4.2/eloquent#timestamps

https://laravel.com/docs/4.2/eloquent#timestamps