php php中的时区转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2505681/
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
Timezone conversion in php
提问by raki
Can anyone suggest an easy method to convert date and time to different timezones in php?
任何人都可以建议一种简单的方法来将日期和时间转换为 php 中的不同时区吗?
回答by Gordon
You can use the datetime object or their function aliases for this:
您可以为此使用 datetime 对象或其函数别名:
Example (abridged from PHP Manual)
date_default_timezone_set('Europe/London');
$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');
Edit regarding comments
编辑评论
but i cannt use this method because i need to show date in different time zones as the user login from different locations
但我无法使用此方法,因为当用户从不同位置登录时,我需要在不同时区显示日期
That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.
那不是问题。当用户登录时,您确定他的时区并将其设置为您的 DateTime 对象,如图所示。我在我的一个项目中使用了类似的方法,它就像一种魅力。
in the database i need to get the dates in any single timezone, then only it can be processed properly
在数据库中,我需要获取任何单个时区的日期,然后才能正确处理
You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.
您可以将时间存储为一个时区中的时间戳或日期时间。当您查询 DateTime 字段时,您可以将 DateTime 对象中的时间转换为此时区,或者 - 如果您的数据库支持它 - 使用所选时区进行查询。
回答by soger
An even simpler method looks like this:
一个更简单的方法如下所示:
date_default_timezone_set('Europe/London'); // your user's timezone
$my_datetime='2013-10-23 15:47:10';
echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));
As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.
如PHP 手册中所述, strtotime() 也接受时区,您只需将其附加到您的日期时间。
I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.
我建议您将所有日期时间存储在 UTC 中,因为这样您就不会遇到夏令时的问题。
回答by saada
This worked for me and it's pretty clean too!
这对我有用,而且也很干净!
function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
$dateTime->setTimezone(new DateTimeZone($userTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
$dateTime->setTimezone(new DateTimeZone($serverTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
//example usage
$serverDate = $userDate = '2014-09-04 22:37:22';
echo convert_to_user_date($serverDate);
echo convert_to_server_date($userDate);
回答by Skeets
None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.
这些答案都不适合我(我跳过了尝试体积过大的代码)。我也认为只为一次转换更改默认时区很奇怪。
Here is my solution:
这是我的解决方案:
function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
{
if (empty($timeZoneSource)) {
$timeZoneSource = date_default_timezone_get();
}
if (empty($timeZoneTarget)) {
$timeZoneTarget = date_default_timezone_get();
}
$dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
$dt->setTimezone(new DateTimeZone($timeZoneTarget));
return $dt->format("Y-m-d H:i:s");
}
So, to convert to the server default, you would just pass one timezone:
因此,要转换为服务器默认值,您只需传递一个时区:
changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");
To convert from the server default to the user, you would leave the 2nd parameter null or blank:
要将服务器默认转换为用户,您可以将第二个参数保留为空或空白:
changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");
And to switch between 2 timezones unrelated to the default, you would provide 2 timezones:
要在与默认值无关的 2 个时区之间切换,您需要提供 2 个时区:
changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");
回答by itsazzad
DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object
DateTime::setTimezone -- date_timezone_set — 设置 DateTime 对象的时区
Object oriented style
面向对象的风格
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
Procedural style
程序风格
<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
上面的例子将输出:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
回答by Eduardo Marcolino
UTC to local:
UTC 到本地:
<?php
$datetime = date("Y-m-d H:i:s");
$utc = new DateTime($datetime, new DateTimeZone('UTC'));
$utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
echo $utc->format('Y-m-d H:i:s');
?>
回答by Hara Prasad
<?php
$time='6:02';
$dt = new DateTime($time, new DateTimeZone('America/New_York'));
//echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
$dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
echo $dt->format('H:i') . PHP_EOL;
?>
回答by user2801665
// Convert date from one zone to another.. /* $zone_from='Asia/Kolkata';
// 将日期从一个区域转换到另一个区域.. /* $zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
回答by Vadim Samokhin
I always struggle to remember how exactly setTimezone()method works. Is it adjusting datetime according to timezone? Or does it take a given datetime, drops its timezone, and uses the one you pass? All in all, I'd rather have a more intuitive way to work with timezones.
我总是很难记住方法究竟是如何setTimezone()工作的。是否根据时区调整日期时间?或者它是否需要给定的日期时间,删除其时区并使用您传递的时区?总而言之,我宁愿有一种更直观的方式来处理时区。
I like this one:
我喜欢这个:
(new AdjustedAccordingToTimeZone(
new DateTimeFromISO8601String('2018-04-25 15:08:01+03:00'),
new Novosibirsk()
))
->value();
It outputs a datetime in ISO8601 format, in Novosibirsk timezone.
它以新西伯利亚时区的 ISO8601 格式输出日期时间。
This approach uses meringue library, check out a quick startfor more examples.
此方法使用蛋白酥皮库,查看快速入门以获取更多示例。

