How to add the current timestamp to the database. What format?

I want to add the current system time to the database by inserting a new record into the database, as in the "time_created" column. PHP time () function does not support in yii2. I need a yii2 time function that will help me save the current timestamp. Somebody knows????

+6
source share
6 answers

Yii 2 has a special behavior for this. Just attach it to the model. Add this to your model to the behaviors() method:

 use yii\behaviors\TimestampBehavior; use yii\db\Expression; public function behaviors() { return [ // Other behaviors [ 'class' => TimestampBehavior::className(), 'createdAtAttribute' => 'time_created', 'updatedAtAttribute' => false, 'value' => new Expression('NOW()'), ], ]; } 
+9
source

You can also use the Yii2 formatter as shown below:

 Yii::$app->formatter->asTimestamp(date('Ydm h:i:s')); //1410488596 Yii::$app->formatter->asDatetime(date('Ydm h:i:s')); //Sep 12, 2014, 2:21:56 AM 
+6
source

It may be outdated, but it may help someone else. Add the code below to your model. Make sure you change createdAttribute to your attribute. You should also include:

 use yii\behaviors\TimestampBehavior; use yii\db\Expression; public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'createdAtAttribute' => 'entry_date', 'updatedAtAttribute' => false, 'value' => new Expression('NOW()'), ], ]; } 
+5
source

You can use yii \ db \ Expression to execute the SQL function

 <?php use yii\db\Expression; $model->time_created = new Expression('NOW()'); $model->save(); 
+3
source

You can simply use the PHP date() function as - date('Ymd H:i:s');

+1
source

There are several ways to add a timestamp, I suggest using a UNIX timestamp to work with the time zone. For example, in the Google SQL examples, you cannot set the time zone but offset, which means that you will need to update the offset twice a year due to summer / winter time. For this, as someone mentioned, you can also use the behavior:

 public function behaviors() { return [ [ 'class' => AttributeBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => 'entry_date', ], 'value' => function ($event) { return time(); }, ], ]; } 

or you can just add before insertion, for example $model->entry_date=time(); , but as you do this on every INSERT , the behavior is better to choose.

And of course, if you want to read a formatted date, you can use:

 \Yii::$app->formatter->asDate($model->entry_date); 

For formatting asDate you can read here: http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html#asDate()-detail

0
source

Source: https://habr.com/ru/post/979320/


All Articles