Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatter asDateTime in yii2

Tags:

yii2

If I have an element array like this :

 [PERKIRAAN_SELESAI] => 24/10/2016 09:38

Then I want to store into datetime format in mysql which is YYYY-MM-DD H:s, => 2016-10-24 09:38

How can Yii2 handle this, Now, in beforeSave(), I use this :

$this->perkiraan_selesai = Yii::$app->formatter->asDateTime(strtorime($this->PERKIRAAN_SELESAI), "php:Y-m-d H:s" );

But, still not working. Please.

like image 923
Fadly Dzil Avatar asked Nov 16 '25 11:11

Fadly Dzil


1 Answers

First of all, I see 2 errors in your code:

  • 2016-10-24 09:38 date looks like a Y-m-d H:i format, not Y-m-d H:s. Check PHP date function docs for interpretation of these letters.

  • strtorime must be strtotime, but I think this typo is not in original code, just here in post.

As for your problem, check this related question on SO. Seems that the problem is with handling of slash (/). Instead of replacing it with - manually, I found solution with native class DateTime much better.

Using plain PHP:

$date = \DateTime::createFromFormat('d/m/Y H:i', '24/10/2016 09:38')->format('Y-m-d H:i');

Using Yii2 formatter:

$date = Yii::$app->formatter->asDateTime(\DateTime::createFromFormat('d/m/Y H:i', '24/10/2016 09:38'), 'php:Y-m-d H:i');

Just replace this date with your value.

The value of $date is 2016-10-24 09:38 as expected.

like image 128
arogachev Avatar answered Nov 19 '25 07:11

arogachev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!