Tomas Grecio Ramirez
Tomas Grecio Ramirez

Reputation: 380

Why Yii2 formatter does not work correctly?

I want to know why the second line throws an error:

Yii::$app->formatter->dateFormat='yyyy-MM-dd';
echo Yii::$app->formatter->format('14/01/2017','date');

And why is there no error in this case?

Yii::$app->formatter->dateFormat='yyyy-MM-dd';
echo Yii::$app->formatter->format('10/07/2015', 'date');

Upvotes: 0

Views: 179

Answers (1)

rob006
rob006

Reputation: 22174

Your date format is ambiguous . You're probably using DD/MM/YYYY format, but PHP interprets this as MM/DD/YYYY. There is no 14th month, so 14/01/2017 is incorrect date. 10/07/2015 does not throw any error, but it is probably incorrectly interpreted as 2015-10-07 instead of 2015-07-10.

You need to parse date before passing it to formatter:

Yii::$app->formatter->dateFormat = 'yyyy-MM-dd';
$date = DateTime::createFromFormat('d/m/Y', '14/01/2017');
echo Yii::$app->formatter->format($date, 'date');

Upvotes: 2

Related Questions