laravel 5.4,如何插入时间戳(mysql)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46814291/
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
laravel 5.4, how to insert a timestamp (mysql)
提问by John Little
In our laravel migrations, we insert static data which is required by the app (countries, currencies etc).
在我们的 Laravel 迁移中,我们插入了应用程序所需的静态数据(国家、货币等)。
We are trying to insert a row with a timestamp field, but cant figure out how to set it to a specifid day/time.
我们正在尝试插入带有时间戳字段的行,但无法弄清楚如何将其设置为特定的日期/时间。
We have tried time() and setting a standard date format, e.g:
我们尝试过 time() 并设置标准日期格式,例如:
DB::table('test')->insert(['id'=>1,'start_at'=>time(), 'end_at'=>'2050-01-01 00:00:00']);
Both timestamp columns end up with 0000-00-00 00:00:00.
两个时间戳列都以 0000-00-00 00:00:00 结尾。
Any ideas?
有任何想法吗?
回答by Joel Hinz
time()
returns a Unix timestamp, but MySQL wants a YYYY-mm-dd HH:ii:ss timestamp. You can use e.g. date('Y-m-d H:i:s')
or try out Carbon.
time()
返回一个 Unix 时间戳,但 MySQL 想要一个 YYYY-mm-dd HH:ii:ss 时间戳。您可以使用 egdate('Y-m-d H:i:s')
或试用Carbon。
By the way, you also have a missing ' prior to start_at
.
顺便说一句,您在start_at
.
回答by John Little
OK, I found one solution (Carbon option given by Joel & Maraboc might be better)
好的,我找到了一个解决方案(Joel & Maraboc 提供的碳选项可能更好)
$now= new DateTime;
$future = $now->add(new DateInterval('P20Y'));
DB::table('test')->insert(['id'=>1,'start_at'=>$now, 'end_at'=>$future]);
回答by Peter Haberkorn
with Carbon:
含碳:
$dt = Carbon::parse('2012-9-5 23:26:11');
var_dump($dt->timestamp); //int(1346901971)
回答by instance
You can also let the DB server do the work:
您还可以让数据库服务器完成这项工作:
'start_at'=>DB::raw('now()')