I setup in config file date format as :
'dateFormat' => 'yy-MM-dd',
but I can't find the way to get dates in this format in active form : I tried :
<?= $form->field($model,
'mydate':date,
but this gives error Any help would be nice :)
You must replace date into needed format by using DateTime.
For example, if you have data in Unix format and want to convert to 'd-M-Y':
\DateTime::createFromFormat('U',$this->date)->format('d-m-Y')
If you always need this conversion, you can create a getter function in model:
public function getDateInFormat()
{
return \DateTime::createFromFormat('U',$this->date)->format('d-m-Y');
}
And the in view:
<?= $form->field($model,$model->dateInFormat); ?>
Here dateFormat
is a property of the \Yii::$app->formatter
component.
In order to explicitly use this setting you should use formatter
\Yii::$app->formatter->asDate($date)
or i18n component
\Yii::t('app', 'The date is: {0,date}', $date);
Also this option is used as default format
in date validator.
So all you need is to add the date
rule (in rules
function of your model):
['mydate', 'date']
And then you can just add in your view
<?= $form->field($model, 'mydate', [])->input('text', []); ?>
In order to work with database you can either manually convert date attribute to/from db format (for example overriding beforeSave
and afterFind
if you work with ActiveRecord) or use timestampAttribute and timestampAttributeFormat in date
validator.
For advanced cases you can use something like yii2-datecontrol.