Managing date formats differences between PHP and MySQL

后端 未结 7 1810
半阙折子戏
半阙折子戏 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:22

    You can replace php_date with strtotime.

    $php = strtotime($mysql);
    

    The MySQL equivalent would be UNIX_TIMESTAMP.

    Though, if you want to handle formatting in SQL, try MySQL's DATE_FORMAT.

    0 讨论(0)
  • 2020-12-09 14:25

    Store everything in the database in a datetime field in UTC. For PHP manipulation, use the PEAR Date library. I'm not a big PEAR user, but this library is fantastic and will handle all of annoying date conversion issues that you should not be spending your time worrying about.

    0 讨论(0)
  • 2020-12-09 14:28

    I think it would be a better ideea to store unix timestamps in the DB field. When you need to display dates to human language, you can always use php's date() function. For everything else, just use the numeric timestamp.

    0 讨论(0)
  • It is best way to save time and date as unix timestamp rather than other formats.

    I have created a class to handle date and time in php. Its easy to use and very very useful

    <?php
    define("NEW_LINE", "</BR>");
    class scTimestamp
    {
        private $timestamp;
        private $year;
        private $month;
        private $day;
        private $hour;
        private $minute;
        private $second;
    
        public function __construct() 
        {
            register_shutdown_function(array($this,'__destruct'));
            $this->setTimestamp($_SERVER['REQUEST_TIME']);
        }
        public function __destruct()
        {
            unset($this->timestamp);
            unset($this->year);
            unset($this->month);
            unset($this->day);
            unset($this->hour);
            unset($this->minute);
            unset($this->second);
        }
        private function rebuildTimestampFromDate()
        {
            $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year);
        }
        private function rebuildDateFromTimestamp()
        {
            $this->day=date('j',$this->timestamp);
            $this->month=date('n',$this->timestamp);
            $this->year=date('Y',$this->timestamp);
            $this->hour=date('g',$this->timestamp);
            $this->minute=date('G',$this->timestamp);
            $this->second=date('s',$this->timestamp);       
        }
        public function setTimestamp($tempTimestamp)
        {
            $this->timestamp=$tempTimestamp;     
            $this->rebuildDateFromTimestamp();
        }
        public function getTimestamp()
        {
            return $this->timestamp;    
        }
        public function setYear($tempYear)
        {
            $this->year = $tempYear;
            $this->rebuildTimestampFromDate();
        }
        public function getYear()
        {
            return $this->year;
        }
        public function setMonth($tempMonth)
        {
            $this->month = $tempMonth;
            $this->rebuildTimestampFromDate();
        }
        public function getMonth()
        {
            return $this->month;
        }
        public function setDay($tempDay)
        {
            $this->day=$tempDay;
            $this->rebuildTimestampFromDate();
        }
        public function getDay()
        {
            return $this->day;
        }
        public function setHour($tempHour)
        {
            $this->hour = $tempHour;
            $this->rebuildTimestampFromDate();
        }
        public function getHour()
        {
            return $this->hour;
        }
        public function setMinute($tempMinute)
        {
            $this->minute = $tempMinute;
            $this->rebuildTimestampFromDate();
        }
        public function getMinute()
        {
            return $this->minute;
        }
        public function setSecond($tempSecond)
        {
            $this->second = $tempSecond;
            $this->rebuildTimestampFromDate();
        }
        public function getSecond()
        {
            return $this->second;
        }
    
    
        public function getDateDifferenceFromNow()
        {
            return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']);
        }
        public function getDateDifferenceFrom($fromDate)
        {
            $return="";
            $sec=" Second";
            $min=" Minute";
            $hrs=" Hour";
            $before=" Before";
            $difference=$fromDate-$this->getTimestamp();
            if($difference<0)
                $return.="In the Future";
            else if($difference<60)
            {
                if($difference>1)
                    $sec.="s";
                $return.= $difference.$sec.$before;
            }
            else if($difference<3600)
            {
                $difference=intval($difference/60);
                if($difference>1)
                    $min.="s";
                $return.=$difference.$min.$before;
            }
            else if($difference<86400)
            {
                $difference=intval($difference/3600);
                if($difference>1)
                    $hrs.="s";
                $return= $difference.$hrs.$before;
            }
            else if($difference<604800)
            {
                $return.= date("l g:i a",$this->getTimestamp());
            }
            else if($difference<28512000)
            {
                $return.= date("F j",$this->getTimestamp());
            }
            else
            {
                $return.= date("F j, Y, g:i a",$this->getTimestamp());
            }
            return $return;
        }
        public function getDateAsString()
        {
            return date("F j, Y",$this->getTimestamp());
        }
        public function getDateTimeAsString()
        {
            return date("F j, Y, g:i a",$this->getTimestamp());
        }
    
    
        public function __toString()
        {
            $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^";
            $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE;
            $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE;
            $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE;
            $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE;
            return $return;
        }
    
    }
    ?>
    

    once it is included it can be used as follow

    include_once("scTimestamp.php");
    $test=new scTimestamp();
    
    echo $test->getDateAsString();
    
    $test->setTimestamp(1210203200);
    
    echo $test->getDateDifferenceFromNow();
    
    echo $test;
    
    $test->setTimestamp(121020320022);
    echo $test->getYear();
    
    echo $test;
    

    And the result would like this.

    June 26, 2015May 7, 2008, 11:33 pm ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ Timestamp: 1210203200 @@ @@ Date: May 7, 2008, 11:33 pm @@ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 5804 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ Timestamp: 121020320022 @@ @@ Date: December 25, 5804, 3:33 am @@ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    This class can be used as per needs

    0 讨论(0)
  • 2020-12-09 14:30

    Since (around) PHP 5.2, PHP has had a built in class/object for dealing with Dates and Times, called DateTime. In a void, it's always better to use a built-in than to wrangle with the messy details yourself.

    The DateTime constructor (or the date_create function) accepts a date in any format understood by strToTime. All you need to know about strToTime is it's magic voodoo that will correctly recognize a date in almost any string format. When I first encountered strToTime I had the same internal reaction you're having now ("that's bullshit/seems unreliable"). It's not. It Just Works in a way that your own fragile understanding of dates never will (and if you think you understand dates, you don't. Trust Me.)

    So, pull the information from MySQL as a Date/Time string, and immediately create a PHP date Object. Use the date_format method (with some handy constants) when/if you need the date again as a string.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题