How to validate dates?

I’m still new to Yii but already like the framework a lot.

Actually I’m stuck to a problem which I’m quite sure is easy to solve for more experienced developers, so I hope for help from this community.

In my class I have these rules defined:




    public function rules()

    {

        return [

            [['user_id', 'status_id'], 'required'],

            [['user_id', 'status_id'], 'integer'],

            [['valid_until'], 'date', 'format'=>'Y-m-d H:m:s'],

        ];

    }



and I have a function to calculate dates:




    private function getDueDate($interval)

    {

        try {

            $date = date_create(NULL , timezone_open("Europe/Berlin"));

        } catch (Exception $e) {

            echo $e->getMessage();

            exit(1);

        }  


        date_add($date, date_interval_create_from_date_string($interval));


        $dueDate = \Yii::$app->formatter->asDate(date_format($date,'Y-m-d H:m:s'), 'php:Y-m-d H:m:s');


        return $dueDate;

    }



If I echo $dueDate it shows me e.g. "2016-06-22 19:06:24" which seems to be well formated.

Anyway I’m unable to save the model as it throws a validation error for valid_until.

If I comment the rule out, it saves to the database.

Any help is very appreciated.

J-C

If you want to set format in date validator you have to remember that syntax is based on ICU formatting guide http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax

If you want to use php date style use "php:" prefix.

I see that you already using "php:" but only in Yii::$app->formatter->asDate.

"Y-m-d H:m:s" is wrong. For ICU it should be "y-MM-dd HH:mm:ss". For php it should be "Y-m-d H:i:s".

Perfect! Thank you so much. This was the hint, I was looking for. Now, it works. :D