2

The $model->datetime is d-m-Y H:i:s.

<?php echo $form->textField($model,'datetime'); ?>

I would like the value of the input just be d-m-Y, how can I format it?

1 Answer 1

3

One option would be to convert the date to a human readable format to display it, and then back to the format needed by the database before you save. You could edit/create the afterFind() method in your model to convert the date to a human readable format, something like so:

public function afterFind()
{
    $newDate = DateTime::createFromFormat('d-m-Y H:i:s', $this->datetime);
    $this->datetime = $newDate->format('d-m-Y');

    return parent::afterFind();
}

And again before you save by editing/creating your model's beforeSave() method, for example something like:

public function beforeSave()
{
    $newDate = DateTime::createFromFormat('d-m-Y', $this->datetime);
    $this->datetime = $newDate->format('d-m-Y H:i:s');

    return parent::beforeSave();
}

Note that when you save, the hour, minute and second will always be 0 in the examples above. You'd also need to put some validation to make sure your user input was in the correct d-m-Y format too, or the date conversion won't work.

*Fixed typo newdate->newDate

Sign up to request clarification or add additional context in comments.

1 Comment

Remember DateTime::createFromFormat() available from PHP 5.3.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.