簡體   English   中英

如何通過PHP輕松轉換UTC的日期?

[英]How can I easily convert dates from UTC via PHP?

我在UTC中的日期時間字段中將日期存儲在MySQL數據庫中。 我正在使用PHP,並且我調用了date_timezone_set('UTC'),以便所有對date()的調用(沒有時間戳)以UTC格式返回日期。

然后,我有它,所以給定的網站可以選擇其時區。 現在我希望日期顯示在網站的時區。 因此,如果我將日期存儲為“2009-04-01 15:36:13”,則應在PDT時區(-7小時)內為用戶顯示為“2009-04-01 08:36:13” 。

通過PHP執行此操作的最簡單(最少代碼)方法是什么? 到目前為止,我所想到的只是

date('Y-m-d H:i:s', strtotime($Site->getUTCOffset() . ' hours', strtotime(date($utcDate))));

有更短的方式嗎?

為什么不使用內置的DateTime / TimeZone功能?

<?php

$mysqlDate = '2009-04-01 15:36:13';

$dateTime = new DateTime ($mysqlDate);
$dateTime->setTimezone(new DateTimeZone('America/Los_Angeles'));

?>

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

PHP支持的時區: http//php.net/manual/en/timezones.php

你正在做的是正確的做事方式。 我建議堅持只使用UTC工作,並在最后一分鍾轉換顯示。

這是我使用PHP附帶的DateTime類進行時區轉換的快速函數。 它比你有更多的代碼,但我認為它更簡單,更好的結構化方式......

function convert_time_zone($date_time, $from_tz, $to_tz)
    {
    $time_object = new DateTime($date_time, new DateTimeZone($from_tz));
    $time_object->setTimezone(new DateTimeZone($to_tz));
    return $time_object->format('Y-m-d H:i:s');
    }

http://richardwillia.ms/blog/2011/04/time-zone-conversion-using-datetime-class/

希望有所幫助。

這是我們對服務器所做的。 我們將所有內容設置為使用UTC,並通過動態轉換顯示在用戶的時區中。 這篇文章底部的代碼是如何使其工作的一個例子; 您應該確認它適用於您的設置(即夏令時等)的所有情況。

配置CentOS

  1. 編輯/etc/sysconfig/clock並將ZONE設置為UTC
  2. ln -sf /usr/share/zoneinfo/UTC /etc/localtime

配置MySQL

  1. 如有必要,將時區導入MySQL:

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

  2. 編輯my.cnf並在[mysqld]部分中添加以下內容:

    default-time-zone = 'UTC'

PHP代碼

<?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);
    }

}
<?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 '';
        }
    }
?>

使用樣本:

<?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
?>

花了很多時間處理這個問題, 不要試圖自己實現時區翻譯。 這是一個充滿困難的皇家PIA,在國際上很難做到這一點。

也就是說,最好的選擇是將MySQL中的日期 時間轉換為時間戳 ,只需使用數據庫轉換時間:

 mysql> set time_zone='America/New_York';

MySQL中的時間戳較小,並支持時區轉換。 datetime沒有。

在頁面上顯示站點信息之前,只需調用上面的命令,它就會正確顯示而根本不需要任何PHP代碼更改。

注意事項:

  1. 如果使用NOW()或任何本地時間函數,則應將它們更新為UTC_TIMESTAMP()
  2. 時間戳有一些有趣的更新和插入屬性,您可能想要關閉它們。

要關閉時間戳屬性:

ALTER TABLE mytable CHANGE COLUMN Created Created timestamp NULL DEFAULT 0;

更新其他列時, DEFAULT 0將禁用正在更新的列。

ADDTIME($utcDate,$Site->getUTCOffset())

這對我有用,而且很干凈

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);
}

使用單個函數將用戶時區轉換為服務器時區,反之亦然:

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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM