【问题标题】:Convert time in PHP from gmt offset从 gmt 偏移量转换 PHP 中的时间
【发布时间】:2014-05-22 15:35:15
【问题描述】:
例如,我有一个“11:00”的时间字符串和一个“+02:00”的gmt偏移字符串。
如何将两者结合起来在 PHP 中进行转换?
这是我当前的代码:
$time = $row->time;
//Get users gmt setting
$timezone = $this->_get_gmt();
//calculate correct time here
$time = ; //whatever i have to do.
感谢所有答案。
【问题讨论】:
标签:
php
datetime
timezone
gmt
date-conversion
【解决方案1】:
$date = DateTime::createFromFormat('H:i P', '11:00 +02:00');
$date->setTimeZone(new DateTimeZone('GMT'));
echo $date->format('H:i');
Demo
这个:
- 创建一个包含时间和偏移量的 DateTime 对象
- 将时区转换为 GMT
- Echo 的 GMT 时间结束
【解决方案2】:
您可以使用DateTime 对象来做到这一点
$date = new DateTime('Your Time String here');
$date->setTimezone(new DateTimeZone('GMT'));
echo $date->format('Y-m-d H:i:sP') . "\n";
【解决方案3】:
试试:
$time = $row->time;
$timezone = $this->_get_gmt();
$time = date( "H:i:s", strtotime( $time )+ $timezone * 60 * 60 )
假设$time 是时间格式:例如。 14:30,$timezone 是偏移量,例如。 2.