使用 Laravel 插入当前日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53755125/
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 18:12:49  来源:igfitidea点击:

insert current date time using laravel

phpmysqllaravelphp-carbon

提问by seema

I want to store current date time in MySQLusing following laravel function. Actually, I stored static date instead of this i want store current date time at created_at,updated_atfield in database.

我想使用以下 laravel 函数在 MySQL 中存储当前日期时间。实际上,我存储的是静态日期而不是这个我想将当前日期时间存储在created_at,updated_at数据库中的字段。

 function insert(Request $req)
   {
       $name=$req->input('name');
       $address=$req->input('address');
       $data=array("name" => $name,"address" => $address,"created_at"=>'2017-04-27 10:29:59',"updated_at"=>'2017-04-27 10:29:59');
       DB::table('student')->insert($data);
       echo "Record inserted successfully.<br/>";
       return redirect('/');
   }

回答by Jignesh Joisar

use laravel helper function

使用 Laravel 辅助函数

now()

other wise used carbonclass

其他明智的使用carbon

Carbon\Carbon::now()

used like that

像那样使用

$data = array("name" => $name,"address" => $address,"created_at"=> Carbon::now(),"updated_at"=> now());
DB::table('student')->insert($data);

for more information see

有关更多信息,请参阅

回答by dhara gosai

use have also use this get to current date time time its work.

使用也使用这个获取当前日期时间时间它的工作。

 $current_date = date('Y-m-d H:i:s');

And also i have update and set in your function you have to put this.

而且我还更新并设置了您的功能,您必须将其放入。

  function insert(Request $req)
 {
   $name=$req->input('name');
   $address=$req->input('address');

   $current_date_time = date('Y-m-d H:i:s');

   $data=array("name" => $name,"address" => $address,"created_at"=> 
   $current_date_time,"updated_at"=>$current_date_time);
   DB::table('student')->insert($data);
   echo "Record inserted successfully.<br/>";
   return redirect('/');

 }

回答by Prathamesh Doke

Hello , use this in your db query.

你好,在你的数据库查询中使用它。

'created_at' => Carbon::now(),
'updated_at' => Carbon::now()

回答by Ravi Sachaniya

You can use the DateTimeobject.

您可以使用该DateTime对象。

Look at below code :

看看下面的代码:

$curTime = new \DateTime();
$created_at = $curTime->format("Y-m-d H:i:s");

$updateTime = new \DateTime();
$updated_at = $updateTime->format("Y-m-d H:i:s");