我有一个数组,其中包含GMT中的时间值。 :
Array
(
[0] => Array
(
[h] => 5
[m] => 0
)
)
这里Array[0][0]
是开始时间的数组,Array[0][1]
是结束时间的数组。
现在,我正在使用日期时间创建时间:
$timezone = new DateTimeZone("Asia/Kolkata"); //Converting GMT to IST.
$startTime = new DateTime();
$startTime->setTime($Array[1][0]["hour"], $Array[1][0]["minute"]);
$startTime->setTimezone($timezone);
$startTime->format('h:i a'); //output 10:30 PM // Should be 10:30 AM
$endTime = new DateTime();
$endTime->setTime($Array[1][1]["hour"], $Array[1][1]["minute"]);
$endTime->setTimezone($timezone);
$endTime->format('h:i a'); //output 10:30 PM //ok
So My $startTime and $endTime both has the same value of `10:30` PM but I want the startTime to have value of `10:00 AM`because its period was `AM` in the array.
创建新的Datetime
对象时必须指定时区,因为默认值取自PHP配置,并且可能不会设置为GMT。所以$startTime
和$endTime
的初始化应该是:
$startTime = new DateTime('', new DateTimeZone('GMT'));
$endTime = new DateTime('', new DateTimeZone('GMT'));
然后,当您使用setTime()
时,您必须在PM时间段内添加12小时。看起来应该是这样的:
$startTime->setTime($Array[1][0]["hour"] + ($Array[1][0]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);
$endTime->setTime($Array[1][1]["hour"] + ($Array[1][1]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);
其余的代码看起来很好,除了你的例子,$Array[1]
是未定义的。 $Array[0]
已经确定。
你也可以使用DateTime::createFromFormat()
:
$d = DateTime::createFromFormat('g:m A', '5:30 PM', new DateTimeZone('GMT'));
$d->setTimeZone(new DateTimeZone('Asia/Kolkata'));
var_dump($d->format('Y-m-d H:i:s'));
得到:
string(19) "2017-03-16 22:30:00"
您可以通过组合数组的元素来创建字符串'5:30 PM'
。请注意,如果小于10,你必须在会议记录中添加一个领先的0
,例如:9分钟 - > 09