簡體   English   中英

如何將php日期格式轉換為GMT,反之亦然?

[英]how to convert php date formats to GMT and vice versa?

我是php的新手。 我想編寫一個函數,我需要用戶以任何日期格式輸入日期,包括DST,GMT格式,然后再回到原來輸入的格式。請任何機構幫助我。

雖然gmdate功能可用。 如果您使用的是PHP 5.2或更高版本,請考慮使用DateTime對象。

這是切換到GMT的代碼

$date = new DateTime();
$date->setTimezone(new DateTimeZone('GMT'));

並返回默認時區...

$date = new DateTime('2011-01-01', new DateTimeZone('GMT'));
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));

使用DateTime對象可以創建日期時間,就像過程函數一樣,除了保留對實例的引用。

例如

// Get a reference to Christmas of 2011, at lunch time.
$date = new DateTime('2011-12-25 13:00:00');

// Print the date for people to see, in whatever format we specify.
echo $date->format('D jS M y');

// Change the timezone to GMT.
$date->setTimezone(new DateTimeZone('GMT'));

// Now print the date/time it would in the GMT timezone
// as opposed to the default timezone it was created with.
echo $date->format('Y-m-d H:i:s');

// Just to show of some more, get the previous Sunday
$date->modify('previous Sunday');

你可以使用很多函數,它們比程序函數更具可讀性。


從時區轉換為GMT的明確示例

$melbourne = new DateTimeZone('Australia/Melbourne');
$gmt = new DateTimeZone('GMT');

$date = new DateTime('2011-12-25 00:00:00', $melbourne);
$date->setTimezone($gmt);
echo $date->format('Y-m-d H:i:s');
// Output: 2011-12-24 13:00:00
// At midnight on Christmas eve in Melbourne it will be 1pm on Christmas Eve GMT.

echo '<br/>';

// Convert it back to Australia/Melbourne
$date->setTimezone($melbourne);
echo $date->format('Y-m-d H:i:s');

使用您的亞洲/加爾各答到美國/紐約

date_default_timezone_set('Asia/Kolkata');
$date = new DateTime('2011-03-28 13:00:00');
$date->setTimezone(new DateTimeZone('America/New_York'));
echo $date->format("Y-m-d H:i:s");
//Outputs: 2011-03-28 03:30:00

使用gmdate函數轉換為GMT時間。

例如

$d = '2011-03-28 12:05:20'; 
$gmt = gmdate('Y-m-d H:i:s',strtotime($d));

//將本地時間轉換為gmt

    public function convertTime($timezone,$time){
        $selectedtime = date("Y-m-d H:i",strtotime($time));
        $date = new DateTime($selectedtime, new DateTimeZone($timezone));
        $date->setTimezone(new DateTimeZone('GMT'));
        $convertedtime = strtotime($date->format('Y-m-d H:i'));
        return $convertedtime;
    }

暫無
暫無

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

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