Best way to save date from datepicker

I have datepicker date in format like so …

15/4/2015

But when saving it to the database obviously it does not save because its in the wrong format.

I use to save it using beforeSave / afterFind in Yii 1, but does Yii 2 offer a better way?

Did you read the documentation ? Property


altFormat

MySql save it as "Y-m-d" format.

I am using kartik\datecontrol for date calender, and you can set format in config file.


'datecontrol' =>  [

            'class' => '\kartik\datecontrol\Module',

            'saveSettings' => [

                Module::FORMAT_DATE => 'php:Y-m-d', // saves as unix timestamp

                Module::FORMAT_TIME => 'php:H:i:s',

                Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',

            ],

        ],

Ok everyone I decided to use Yii 2 behaviors like so …




public function behaviors() {

			

			return [

				

				"dueDateBeforeSave" => [

					

					"class" => TimestampBehavior::className(),

					"attributes" => [

						ActiveRecord::EVENT_BEFORE_INSERT => "dueDate",

						ActiveRecord::EVENT_BEFORE_UPDATE => "dueDate",

					],

					"value" => function() { return Yii::$app->formatter->asDate($this->dueDate, "Y-MM-dd"); }

					

				],

				

				"dueDateAfterFind" => [

					

					"class" => TimestampBehavior::className(),

					"attributes" => [

						ActiveRecord::EVENT_AFTER_FIND => "dueDate",

					],

					"value" => function() { return Yii::$app->formatter->asDate($this->dueDate, "MM/dd/Y"); }

					

				]

				

			];

			

		}



Using altFormat requires the creation of a hidden altField.

Meaning you need two fields per datepicker, a visible one and a hidden one. Hence I do not think this is the best way to re-format a submitted date to be stored in the DB.

Your solution collide with built-in date validator. doc

Ok well I will be coming to that in a bit, so I will see if any errors come up when I do it.