我在这里问,我知道还有其他问题和答案,我一直在通过它们:在PHP中计算两个日期之间的小时数
但是我仍然找不到解决问题的方法。情况是这样的:我使用谷歌日历Api。我有一个foreach()
循环在运行,它画出事件的dateTime()
。我想要得到开始和结束时间的差值。我的代码如下:
$neweventDateStr = new DateTime($event->start->dateTime);
$neweventDateEnd = new DateTime($event->end->dateTime);
$diff = $eventDateEnd->diff($neweventDateStr);
然而,我在最后一行得到以下错误:
Fatal error: Call to a member function diff() on string
我已经检查过了,两个变量都被识别为dateTime对象。因此,我不知道为什么给我上面列出的错误。知道为什么会这样吗?
注意,代码:
$event->start->dateTime
以dateTime RFC 3339格式从google服务器返回日期和时间的值:https://developers.google.com/google-apps/calendar/v3/reference/events
返回如下值:
$event->start->dateTime = 2015-07-06T14:30:00+02:00
$event->se->dateTime = 2015-07-06T15:30:00+02:00
I have try to:
echo $neweventDateStr;
and i返回错误(如预期的那样),该变量无法转换为字符串,因为它是dateTime
对象格式。
问题出在你的代码中:-
$diff = $eventDateEnd->diff($neweventDateStr);
应该是:-
$diff = $neweventDateEnd->diff($neweventDateStr); // because no where $eventDateEnd is defined.
示例如下:—
<?php
$neweventDateStr = new DateTime('2015-04-04 10:10:10');
$neweventDateEnd = new DateTime('2015-04-10 10:10:10');
$diff = $neweventDateEnd->diff($neweventDateStr); // instead of $eventDateEnd i write $neweventDateEnd
print_r($diff);
?>
输出:https://eval.in/393320