How to implement class to format date?

Hi there,

I am very new to Yii2 so still trying to get the hang of everything.

I’m trying to create and call a class to format dates to integer before saving to db that I got from this tutorial (Tip#4)

http://www.yiiframework.com/wiki/684/save-and-display-date-time-fields-in-different-formats-in-yii2/

Here is the excerpt from the tutorial:

Tip 4: Easily convert any attribute format before saving to db

In case you do not wish to use the extension as mentioned in Tip # 1, you can create your own global formats for save. Just create a helper class like this:


class Setup {

    const DATE_FORMAT = 'php:Y-m-d';

    const DATETIME_FORMAT = 'php:Y-m-d H:i:s';

    const TIME_FORMAT = 'php:H:i:s';

 

    public static function convert($dateStr, $type='date', $format = null) {

        if ($type === 'datetime') {

              $fmt = ($format == null) ? self::DATETIME_FORMAT : $format;

        }

        elseif ($type === 'time') {

              $fmt = ($format == null) ? self::TIME_FORMAT : $format;

        }

        else {

              $fmt = ($format == null) ? self::DATE_FORMAT : $format;

        }

        return \Yii::$app->formatter->asDate($dateStr, $fmt);

    }

}

Then anywhere else (like controller/model) you can access this function to convert any input date/time string for saving to database.


$model->dateAttr = Setup::convert($model->dateAttr);

$model->datetimeAttr = Setup::convert($model->datetimeAttr, 'datetime');

Here is my modified code:

Controller:


public function actionCreate()

    {

        $model = new Projects();

 

        if ($model->load(Yii::$app->request->post())) {

			$model->date_created = formatDate::convert($model->date_created);

           if ($model->save()) {             

             return $this->redirect(['view', 'id' => $model->id]);             

           } 

        } 

        return $this->render('create', [

            'model' => $model,

        ]);

    }

frontend/components/formatDate.php:


<?php


namespace frontend\components;


class formatDate {

    const DATE_FORMAT = 'php:yyyymmdd';

    const DATETIME_FORMAT = 'php:yyyymmddHis';

    const TIME_FORMAT = 'php:His';

 

    public static function convert($dateStr, $type='date', $format = null) {

        if ($type === 'datetime') {

              $fmt = ($format == null) ? self::DATETIME_FORMAT : $format;

        }

        elseif ($type === 'time') {

              $fmt = ($format == null) ? self::TIME_FORMAT : $format;

        }

        else {

              $fmt = ($format == null) ? self::DATE_FORMAT : $format;

        }

        return \Yii::$app->formatter->asDate($dateStr, $fmt);

    }

}

frontend/config/main-local.php:




...

'formatDate' => [

 

            'class' => 'frontend\components\formatDate',

 

            ],

...

When I use the CRUD form to create a new project, the page just reloads without error. Can someone please tell me what I am doing wrong?