Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.


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 ?


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];

$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


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()");