How can I easily convert dates from UTC via PHP?

前端 未结 8 2334
梦谈多话
梦谈多话 2020-12-01 17:07

I am storing dates in a MySQL database in datetime fields in UTC. I\'m using PHP, and I\'ve called date_timezone_set(\'UTC\') so that all calls to date() (without timestamp)

相关标签:
8条回答
  • 2020-12-01 17:30

    Why not use the built in DateTime/TimeZone functionality?

    <?php
    
    $mysqlDate = '2009-04-01 15:36:13';
    
    $dateTime = new DateTime ($mysqlDate);
    $dateTime->setTimezone(new DateTimeZone('America/Los_Angeles'));
    
    ?>
    

    DateTime Class: http://us3.php.net/manual/en/class.datetime.php DateTimeZone Class: http://us3.php.net/manual/en/class.datetimezone.php

    PHP's supported Timezones: http://php.net/manual/en/timezones.php

    0 讨论(0)
  • 2020-12-01 17:31

    Here's what we did with our servers. We set everything to use UTC, and we display in the user's time zone by converting from UTC on the fly. The code at the bottom of this post is an example of how to get this to work; you should confirm that it works in all cases with your setup (i.e. daylight savings, etc).

    Configuring CentOS

    1. Edit /etc/sysconfig/clock and set ZONE to UTC
    2. ln -sf /usr/share/zoneinfo/UTC /etc/localtime

    Configuring MySQL

    1. Import timezones into MySQL if necessary:

      mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

    2. Edit my.cnf and add the following within the [mysqld] section:

      default-time-zone = 'UTC'

    PHP Code

    <?php
    /*
    Example usage:
      $unixtime = TimeUtil::dateTimeToTimestamp('2009-04-01 15:36:13');
      echo TimeUtil::UTCToPST("M d, Y - H:i:s", $unixtime);
    */
    
    // You should move this to your regular init method
    date_default_timezone_set('UTC'); // make this match the server timezone
    
    class TimeUtil {
        public static function timestampToDateTime($timestamp) {
            return gmdate('Y-m-d H:i:s', $timestamp);
        }
    
        public static function dateTimeToTimestamp($dateTime) {
            // dateTimeToTimestamp expects MySQL format
            // If it gets a fully numeric value, we'll assume it's a timestamp
            // You can comment out this if block if you don't want this behavior
            if(is_numeric($dateTime)) {
                // You should probably log an error here
                return $dateTime;
            }
            $date = new DateTime($dateTime); 
            $ret = $date->format('U');
            return ($ret < 0 ? 0 : $ret);
        }
    
        public static function UTCToPST($format, $time) {
            $dst = intval(date("I", $time));
            $tzOffset = intval(date('Z', time()));
            return date($format, $time + $tzOffset - 28800 + $dst * 3600);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-01 17:34

    Convert user timezone to server timezone and vice versa, with a single function:

    function convertTimeZone($date, $convertTo = 'userTimeZone', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC', $format = 'n/j/Y g:i A')
    {
        if($convertTo == 'userTimeZone'){
           $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
           $dateTime->setTimezone(new DateTimeZone($userTimeZone));
           return $dateTime->format($format);   
        } else if($convertTo == 'serverTimeZone'){
           $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
           $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
           return $dateTime->format($format);   
        }
    }
    
    echo convertTimeZone(date('Ydm h:i:s'),'serverTimeZone');
    
    0 讨论(0)
  • 2020-12-01 17:43
    <?php
    
      function getNoteDateTimeZone($date = null, $from_dtz = 'US/Central', $to_dtz = null) {
            //$from_zt = 'US/Central'; // Time Zone = -06:00
            if (is_null($date) == FALSE && is_null($from_dtz) == FALSE && is_null($to_dtz) == FALSE) {
                // set TimeZone from
                $time_object = new DateTime($date, new DateTimeZone($from_dtz));
                $time_now_object = new DateTime("now", new DateTimeZone($from_dtz));
                // Change TimeZone
                $time_object->setTimezone(new DateTimeZone(trim($to_dtz)));
                $time_now_object->setTimezone(new DateTimeZone(trim($to_dtz)));
                // Is day = day in $time_now_object, $time_object..?
                if ($time_now_object->format('d') == $time_object->format('d')) {
                    return $time_object->format('H:i:s');
                } else {
                    return $time_object->format('Y-m-d H:i:s');
                }
            } else {
                return '';
            }
        }
    ?>
    

    Use sample:

    <?php 
     $date = '2008-06-02 20:32:46';
     $dtz = 'America/Argentina/Buenos_Aires';
     echo getNoteDateTimeZone($date, 'US/Central', $dtz); // Out = 2008-06-02 23:32:46
    ?>
    
    0 讨论(0)
  • 2020-12-01 17:51
    ADDTIME($utcDate,$Site->getUTCOffset())
    
    0 讨论(0)
  • 2020-12-01 17:53

    This worked for me and it's pretty clean

    function convert_to_user_date($date, $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC', $format = 'n/j/Y g:i A')
    {
        $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
        $dateTime->setTimezone(new DateTimeZone($userTimeZone));
        return $dateTime->format($format);
    }
    
    function convert_to_server_date($date, $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC', $format = 'n/j/Y g:i A')
    {
        $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
        $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
        return $dateTime->format($format);
    }
    
    0 讨论(0)
提交回复
热议问题