Managing date formats differences between PHP and MySQL

后端 未结 7 1809
半阙折子戏
半阙折子戏 2020-12-09 13:53

I\'m writing my first PHP app that has to directly deal with dates, and thus to directly deal with the fact that PHP and MySQL have different date formats.

My questi

7条回答
  •  自闭症患者
    2020-12-09 14:32

    You could make a small date object which simply converts the date as you need it

    $Date_p = new MagicDate($php_date);
    $Date_m = new MagicDate($mysql_date);
    

    The $Date_p and $Date_m are just showing that you can seed the object anyway you need to. When you want a mysql date you would have code like. Realistically it would be something pretty generic like $Date.

    $query = "UPDATE SET Date='".$Date_p->toMysql()."' "...
    

    and vice versa when you need the opposite. You can use the functions you've already created. Just add a "sniffer" in the construct method like:

    public function __construct($date)
    {
        $phpdate = strtotime($date);
        if($phpdate) 
        {
            $this->phpdate = $phpdate;
            $this->mysqldate = $this->mysql_date($phpdate);
        }
        else
        {
            $this->phpdate = $this->php_date($phpdate);
            $this->mysqldate = $phpdate;
        }
    }
    

    Throw some error handling in to catch the things that go bad. Add the getter for the two dates. And it's a set it and forget it situation. Just pull the right date out when you need it.

    There could be some optimizations, but this is to just show you how it could work.

提交回复
热议问题