We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

MySQL insert date using ORM

I want to insert date into a Mysql table. The application will get date in the format of (dd/mm/yyyy). How can I insert the date into the table using phalcon PHP ORM ?

edited Mar '14

You can use a beforeSave hook in your model to convert the format of your date to mysql


class Model extends \Phalcon\Mvc\Model
{
    public function beforeSave()
    {
        $this->date = date_format(new \Datetime($this->date), 'Y-m-d');
    }
}

I don't think you can use beforeSave(), because at that point, the query is already built. I think you'll just have to set the date in the controller.



24.2k

I do lot search on google to find how to change date format in PHP but I can't find any. Can you help me to convert dd/mm/yyyy to yyyy/mm/dd format in PHP ?



7.9k
Accepted
answer

if you are sure that $date has always the format dd/mm/yyyy that will work for you :

$date = "19/04/2014";
$elements = explode("/", $date);
$correctDate = $elements[2] . "/" . $elements[1] . "/" . $elements[0];


3.2k
Accepted
answer
$olddate = "31/03/2014";
$date = DateTime::createFromFormat("d/m/Y", $olddate);
$newdate = $date->format('Y/m/d');

and I'm pretty sure you can modify the model's properties in the beforeSave() method, I do that all the time



24.2k

Thanks it works.

edited Aug '17

This is not the best approach. If the database has column defined as TIMESTAMP or DATETIME, you should just pass now() to that model property and that way force database layer to write the correct date (and time).

But with ORM, I'm not sure this is possible.

date from datebase:

new \Phalcon\Db\RawValue("now()");