如何在 PHP 中获得格林威治标准时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/851574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get Greenwich Mean Time in PHP?
提问by drikoda
I have a server which is set to EST, and all records in the database are set to EST. I would like to know how to set it to GMT. I want to offer a time zone option to my users.
我有一个设置为 EST 的服务器,并且数据库中的所有记录都设置为 EST。我想知道如何将其设置为 GMT。我想为我的用户提供时区选项。
回答by nickf
I would stronglysuggest avoiding messing with UNIX timestamps to make it look like a different time zone. This is a lesson I've learnt the hard way, way too many times.
我强烈建议避免弄乱 UNIX 时间戳,使其看起来像不同的时区。这是我学到的教训,太多次了。
A timestamp is the number of seconds since Midnight 1 January 1970, GMT. It doesn't matter where you are in the world, a given timestamp represents the exact same moment in time, regardless of time zones. Yes, the timestamp "0" means 10am 1/1/70 in Australia, Midnight 1/1/70 in London and 5pm 31/12/69 in LA, but this doesn't mean you can simply add or subtract values and guarantee accuracy.
时间戳是自格林威治标准时间 1970 年 1 月 1 日午夜以来的秒数。无论您身在何处,给定的时间戳都代表完全相同的时刻,而与时区无关。是的,时间戳“0”表示澳大利亚的 10am 1/1/70、伦敦的 Midnight 1/1/70 和 5pm 的 31/12/69 在 LA,但这并不意味着您可以简单地添加或减去值并保证准确性。
The golden example which stuffed me up every year for way too long was when daylight savings would crop up. Daylight savings means that there are "clock times" which don't exist in certain parts of the world. For example, in most parts of the US, there was no such time as 2:01am on April 2, 2006.
每年让我感到厌烦太久的黄金例子是夏令时出现的时候。夏令时意味着世界某些地区不存在“时钟时间”。例如,在美国大部分地区,没有 2006 年 4 月 2 日凌晨 2:01 这样的时间。
Enough quasi-intelligible ranting though. My advice is to store your dates in the database as timestamps, and then...
足够的准可理解的咆哮。我的建议是将您的日期作为时间戳存储在数据库中,然后...
- If you need the local time at the server, use
date() - If you need to get GMT, then use
gmdate() - If you need to get a different timezone, use
date_default_timezone_set()and thendate()
- 如果您需要服务器的本地时间,请使用
date() - 如果您需要获得 GMT,请使用
gmdate() - 如果您需要获得不同的时区,请使用
date_default_timezone_set()然后date()
For example,
例如,
$timestamp = time();
echo "BRISBANE: " . date('r', $timestamp) . "\n";
echo " UTC: " . gmdate('r', $timestamp) . "\n";
date_default_timezone_set('Africa/Johannesburg');
echo " JOBURG: " . date('r', $timestamp) . "\n";
// BRISBANE: Tue, 12 May 2009 18:28:20 +1000
// UTC: Tue, 12 May 2009 08:28:20 +0000
// JOBURG: Tue, 12 May 2009 10:28:20 +0200
This will keep your values clean (you don't have to be worrying about adding offsets, and then subtracting before saving), it will respect all Daylight Savings rules, and you also don't have to even look up the timezone of the place you want.
这将使您的值保持干净(您不必担心添加偏移量,然后在保存之前减去),它将遵守所有夏令时规则,您甚至不必查找该地点的时区你要。
回答by p01nd3xt3r
No matter in which GMT time zone the server is, here is an extremely easy way to get time and date for any time zone. This is done with the time()and gmdate()functions. The gmdate()function normally gives us GMT time, but by doing a trick with the time()function we can get GMT+N or GMT-N, meaning we can get the time for any GMT time zone.
无论服务器在哪个 GMT 时区,这里都有一种非常简单的方法来获取任何时区的时间和日期。这是通过time()和gmdate()函数完成的。该gmdate()函数通常为我们提供 GMT 时间,但通过对time()函数进行一些技巧,我们可以获得 GMT+N 或 GMT-N,这意味着我们可以获得任何 GMT 时区的时间。
For example, if you have to get the time for GMT+5, you can do it as follows
例如,如果您必须获得 GMT+5 的时间,您可以按如下方式进行
<?php
$offset=5*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()+$offset);
?>
Now if you have to get the time for GMT-5, you can just subtract the offset from the time()instead of adding to it, like in the following example where we are getting the time for GMT-4
现在,如果您必须获得 GMT-5 的时间,您可以从 中减去偏移量time()而不是添加它,就像在下面的示例中我们获得 GMT-4 的时间
<?php
$offset=4*60*60; //converting 4 hours to seconds.
$dateFormat="d-m-Y H:i"; //set the date format
$timeNdate=gmdate($dateFormat, time()-$offset); //get GMT date - 4
?>
回答by Ahmad Tahboub
Here is a list of the time zones with different from GMT, hope this is helpful!
这是与 GMT 不同的时区列表,希望对您有所帮助!
echo '<pre>';
$zones_array = array();
$timestamp = time();
# to maintain the original timezone, store before
$default_timezone = date_default_timezone_get();
foreach (timezone_identifiers_list() as $key => $zone) {
date_default_timezone_set($zone);
$zones_array[$key]['zone'] = $zone;
$zones_array[$key]['diff_from_GMT'] = date('P', $timestamp);
}
# to maintain the original timezone, re-set after
date_default_timezone_set($default_timezone);
print_r($zones_array);
Thanks!
谢谢!
回答by Alistair Burns
It is important to note that if you are using date('Z') to convert a date that is stored in a database that you give the date the timestamp as the second argument, otherwise your result will not be accurate.
重要的是要注意,如果您使用 date('Z') 转换存储在数据库中的日期,则将日期作为第二个参数的时间戳,否则您的结果将不准确。
e.g.
例如
In the UK, sometimes date('Z') will give 3600, sometimes it will give 0.
在英国,有时 date('Z') 会给出 3600,有时会给出 0。
echo date('Z', strtotime('2012-01-01'));
Gives 0
给 0
echo date('Z', strtotime('2012-07-01'));
Gives 3600
赠送3600
So purely using strtotime($dbDateValue) - date('Z') can be wrong
所以纯粹使用 strtotime($dbDateValue) - date('Z') 可能是错误的
Instead use:
而是使用:
$dbDateTimestamp = strtotime($dbDateValue); // where $dbDateValue something like 2012-01-01 22:34:00
$utcTimestamp = strtotime($dbDateTimestamp) - date('Z', $dbDateTimestamp);
This of course relies on PHP and the database both being set to the same timezone.
这当然依赖于 PHP 和数据库都被设置为相同的时区。
回答by ihtus
I was inspired by this question to write an alternative function to convert a timestamp to a needed timezone.
我受到这个问题的启发,编写了一个替代函数来将时间戳转换为所需的时区。
So, CORRECT procedure steps to record, display (convert) time:
所以,正确的程序步骤来记录、显示(转换)时间:
1) record timestamp with time()
2) If you need to get a different timezone, use:
2.1) Class based:
2.1.1) DateTime class + setTimezone
or
2.1.2) date_default_timezone_set() and then date()
2.1.1) is better and more flexible than 2.1.2)
Function:
function getLTime_class($ts, $uTZ, $format_str="Y.m.d H:i", $sTZ="America/Toronto"){
// $ts - timestamp recorded with time(); if have date => convert to timestamp: strtotime($date_input); //for ex strtotime('2012-02-17 12:00:00'); => 1345219200 - same value for summer and winter (for toronto timezone);
// $uTZ - TZ string (ex: 'America/Toronto'); convert timestamp to this TimeZone
// $sTZ - TZ string (ex: 'America/Toronto'); convert timestamp from this TimeZone
$TimeZone_server=new DateTimeZone($sTZ);
$date_obj=new DateTime("@$ts", $TimeZone_server);
$TimeZone_local=new DateTimeZone($uTZ);
$date_obj->setTimeZone($TimeZone_local);
return $date_obj->format($format_str);
}
Usage:
$date_input=$_POST['date_input']; //read from POST
$ts=strtotime($date_input); //for ex strtotime('2012-02-17 12:00:00'); => 1345219200 - same value for summer and winter (for toronto timezone);
$userTZ='America/Toronto'; //read from user params
$result=getLTime_class($ts, $userTZ, 'Y-m-d H:i:s');
2.2) Non-Class based:
Function:
//this function replaces the function with DateTime class. It's faster. $uTZoffset is integer.
function getLTime_nonclass($ts, $uTZoffset, $format_str="Y.m.d H:i"){
// $ts - timestamp recorded with time(); if have date => convert to timestamp: strtotime($date_input); //for ex strtotime('2012-02-17 12:00:00'); => 1345219200 - same value for summer and winter (for toronto timezone);
// $uTZoffset - TZ offset (integer) $uTZoffset must consider DTS (for ex: in summer $uTZoffset=-4; in winter $uTZoffset=-5)
$ts_offset=date('Z',$ts);
if ($uTZoffset) $add_offset=$ts_offset-date('Z'); //when not UTC
else $add_offset=0; //when UTC
return date($format_str,$ts-$ts_offset+$uTZoffset*3600+$add_offset);
}
Usage:
$date_input=$_POST['date_input']; //read from POST
$ts=strtotime($date_input); //for ex strtotime('2012-02-17 12:00:00'); => 1345219200 - same value for summer and winter (for toronto timezone);
$uTZoffset=-4; //read from user params. $uTZoffset - TZ offset (integer) $uTZoffset must consider DTS (for ex: in summer $uTZoffset=-4; in winter $uTZoffset=-5)
$result=getLTime_nonclass($ts, $uTZoffset, 'Y-m-d H:i:s');
Results:
结果:
$date_input = 2012-08-17 12:00:00
$date_input = 2012-08-17 12:00:00
Server date: summer (2013-08-26)
getLTime_class => $userTZ='America/Toronto' => 2012-08-17 12:00:00
getLTime_nonclass => $uTZoffset=-4 => 2012-08-17 12:00:00
getLTime_class => $userTZ='UTC' => 2012-08-17 16:00:00
getLTime_nonclass => $uTZoffset=0 => 2012-08-17 16:00:00
Server date: winter (2013-02-26)
getLTime_class => $userTZ='America/Toronto' => 2012-08-17 12:00:00
getLTime_nonclass => $uTZoffset=-5 => 2012-08-17 12:00:00
getLTime_class => $userTZ='UTC' => 2012-08-17 16:00:00
getLTime_nonclass => $uTZoffset=0 => 2012-08-17 16:00:00
$date_input = 2012-02-17 12:00:00
$date_input = 2012-02-17 12:00:00
Server date: summer (2013-08-26)
getLTime_class => $userTZ='America/Toronto' => 2012-02-17 12:00:00
getLTime_nonclass => $uTZoffset=-4 => 2012-02-17 12:00:00
getLTime_class => $userTZ='UTC' => 2012-02-17 17:00:00
getLTime_nonclass => $uTZoffset=0 => 2012-02-17 17:00:00
Server date: winter (2013-02-26)
getLTime_class => $userTZ='America/Toronto' => 2012-02-17 12:00:00
getLTime_nonclass => $uTZoffset=-5 => 2012-02-17 12:00:00
getLTime_class => $userTZ='UTC' => 2012-02-17 17:00:00
getLTime_nonclass => $uTZoffset=0 => 2012-02-17 17:00:00
I decided to getLTime_nonclass hoping to make the conversion faster than using classes. All I ask is to confirm that getLTime_nonclass is a valid replacement for getLTime_class. Please feel free to express your opinion. Thanks
我决定 getLTime_nonclass 希望比使用类更快地进行转换。我所要求的只是确认 getLTime_nonclass 是 getLTime_class 的有效替代品。请随时发表您的意见。谢谢
回答by realmag777
A lot of time there is task when necessary record time in DB in GMT+0, but function time() will return time of the server. Its possible resolve by next function:
很多时候有任务需要在 GMT+0 记录时间在 DB 中,但是函数 time() 会返回服务器的时间。它可能由下一个函数解决:
/**
* Converts a local Unix timestamp to GMT
*
* @param int Unix timestamp
* @return int
*/
function local_to_gmt($time = '')
{
if ($time === '')
{
$time = time();
}
return mktime(
gmdate('G', $time),
gmdate('i', $time),
gmdate('s', $time),
gmdate('n', $time),
gmdate('j', $time),
gmdate('Y', $time)
);
}

