3

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.

Fadly Dzil
  • 2,154
  • 3
  • 34
  • 85

1 Answers1

4

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.

Community
  • 1
  • 1
arogachev
  • 33,150
  • 7
  • 114
  • 117