PHP日期显示不正确的时间



我有:

    public function getTime() {
        // first line of PHP
        $defaultTimeZone = 'America/New_York';
        parent::p('date_default_timezone_get():'.date_default_timezone_get());
        if( date_default_timezone_get() != $defaultTimeZone ) { 
            date_default_timezone_set($defaultTimeZone); 
        }
        parent::p( 'System Date/Time: '.date("Y-m-d | h:i:sa") );
        parent::p( 'New York Date/Time: '.$this->_date("Y-m-d | h:i:sa", false, 'America/New_York') );
        parent::p( 'Belgrade Date/Time: '.$this->_date("Y-m-d | h:i:sa", false, 'Europe/Belgrade') );
        parent::p( 'Belgrade Date/Time: '.$this->_date("Y-m-d | h:i:sa", 514640700, 'Europe/Belgrade') );
    }
    private function _date($format="r", $timestamp=false, $timezone=false) {
        $userTimezone = new DateTimeZone(!empty($timezone) ? $timezone : 'America/New_York');
        $edtTimezone = new DateTimeZone('America/New_York');
        $myDateTime = new DateTime(($timestamp!=false?date("r",(int)$timestamp):date("r")), $edtTimezone);
        $offset = $userTimezone->getOffset($myDateTime);
        return date($format, ($timestamp!=false?(int)$timestamp:$myDateTime->format('U')) + $offset);
    }

父::p()只是打印到错误日志,以便于调试,这些是我得到的值:

[18-May-2015 20:56:48 America/New_York] date_default_timezone_get():America/New_York
[18-May-2015 20:56:48 America/New_York] System Date/Time: 2015-05-18 | 08:56:48pm
[18-May-2015 20:56:48 America/New_York] New York Date/Time: 2015-05-18 | 04:56:48pm
[18-May-2015 20:56:48 America/New_York] Belgrade Date/Time: 2015-05-18 | 10:56:48pm
[18-May-2015 20:56:48 America/New_York] Belgrade Date/Time: 1986-04-23 | 08:45:00am

问题是系统日期/时间和纽约日期/时间应该是相同的,但它们不是。为什么会有所不同,我该如何解决这个问题?

$userTimezone->getOffset()返回GMT的偏移量

http://php.net/manual/en/datetimezone.getoffset.php


我更喜欢这种方法。我个人认为代码更可读

   private function _date($format="r", $timestamp=false, $timezone=false) {
        // cache the current timezone
        $tz = date_default_timezone_get();
        if (!empty($timezone)) {
            // temporarily set desired timezone
            date_default_timezone_set($timezone);
        }
        // render date in desired timezone
        $date = date($format, $timestamp ? $timestamp : time());
        // restore cached timezone
        date_default_timezone_set($tz);
        return $date;
    }
输出:

2015-05-18 10:28:48pm: date_default_timezone_get():America/New_York
2015-05-18 10:28:48pm: System Date/Time: 2015-05-18 | 10:28:48pm
2015-05-18 10:28:48pm: New York Date/Time: 2015-05-18 | 10:28:48pm
2015-05-18 10:28:48pm: Belgrade Date/Time: 2015-05-19 | 04:28:48am
2015-05-18 10:28:48pm: Belgrade Date/Time: 1986-04-23 | 01:45:00pm

相关内容

  • 没有找到相关文章

最新更新