繁体   English   中英

PHP date_create函数,使用时区缩写将UTC时间转换为不同的时区

[英]PHP date_create function, converting UTC time to different timezone using the timezone abbrev

$placename=timezone_name_from_abbr("", $timezone * 3600, false);
                        $date = date_create($list['stamp'], timezone_open($placename));
                        $datetimezone=new DateTimeZone('Europe/London');
                        $dateTime = new DateTime($list['stamp'],$datetimezone); 
                        $dateTime->setTimeZone(new DateTimeZone($placename)); 

编辑

我尝试了以下代码建议作为答案,它产生了一个时间,它本应该是2小时。 我检查了我的数据库,数据库中的时间与GMT匹配。 所以问题在于使用转换从GMT转换它

$timezone=-4

来自用户的代码回答,下面产生两个小时的时间。 从GMT转换到America / New_York,但它慢了两个小时。 我检查了placename变量以确保它是America / New_York。 可能是什么导致了这个?

$placename=timezone_name_from_abbr("", $timezone * 3600, true);
$dateTime = new DateTime($list['stamp']); 
$dateTime->setTimeZone(new DateTimeZone($placename)); 
echo $dateTime->format('F d g:i a'); 

原始问题

而不是将其转换为America / New_York时间,这产生了我存储在我的数据库中的UTC时间,为什么这样,为什么它没有转换时间? 它存储在db中2012-05-13 07:30:47

$placename=timezone_name_from_abbr("", $timezone * 3600, true);
$date = date_create($list['stamp'], timezone_open($placename));
echo date_format($date, 'F d g:i a');
$dateTime = new DateTime($date,new DateTimeZone('Europe/London')); 
$dateTime->setTimeZone(new DateTimeZone('America/New_York')); 
echo $dateTime->format('F d g:i a'); 

请注意,我在创建DateTime对象时添加了第二个参数,以确保它知道我传递的是GMT时间,其他方式它将假设其服务器本地时间并可能最终得到不同的结果。

到没有引号的第一个版本。

顺便说一句,你在(在你的代码上)分配一个没有引号的字符串,这可能会或可能不会导致错误,因为PHP将尝试寻找一个名为America的常量并将其除以常量名New_York但我是假设那不是你想要的。

如果您发现所有警告/通知/错误,您会看到以下内容:

Notice: Use of undefined constant America - assumed 'America' in line 3;

其中,如果你想考虑它最终会返回一个实际的警告(前两个是通知)告诉你你的潜水为零。 从某种意义上讲,PHP是危险的,它可以让你做各种疯狂的事情而不会明显地破坏任何东西。 不要误会我的意思,我喜欢PHP,你最初需要小心。

我给你的代码工作:)

如果你没有在创建时指定时区(作为构造函数的第二个参数),它将假设时区是你当前的时区(服务器一个),你可以通过将GMT一个传递到那里或者你的任何东西来覆盖它。 ve存储在数据库中。

但是,文档中有一条警告说:注意:

当$ time参数是UNIX时间戳(例如@ 946684800)或指定时区(例如2010-01-28T15:00:00 + 02:00)时,将忽略$ timezone参数和当前时区。

文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM