试图比较DateTime对象及其错误,为什么?

时间:2015-10-27 15:16:58

标签: php datetime

 $dtStart=new DateTime($item["start"]["dateTime"]);
   $dtEnd  =new DateTime($item["end"]["dateTime"]);
   $dtStGoogle= new DateTime($event->start->dateTime);
   $dtStGoogle->setTimezone(new DateTimeZone("America/Chicago"));
   $dtEndGoogle=new DateTime($event->end->dateTime);
   $dtEndGoogle->setTimezone(new DateTimeZone("America/Chicago"));
   $dtDiffStart=$dtStart->diff($dtStGoogle);
   $dtDiffEnd=$dtEnd->diff($dtEndGoogle);

我使用的是PHP 5.6.13和现在的5.6.14 然后我尝试比较它们,结果总是 true 或始终 false ,无论值是什么。

  if ($dtDiffEnd) { printf("<br> Start Date time are different %d %d %d  %d %d %d ",$dtDiffStart->m,$dtDiffStart->d,$dtDiffStart->y,$dtDiffStart->h,$dtDiffStart->m,$dtDiffStart->s);}   incorrect
  if (!$dtDiffEnd) { same as above} incorrect
  if ($dtStart!=$dtStartGoogle) {same as above} incorrect
  if ($dtStart!==$dtStartGoogle) {same as above} incorrect

我得到的结果的值为0 0 0 0 0 0(总是为真)或无(总是为假),两者都不正确。我尝试了其他同样结果的疯狂事情。

我已经尝试过所有我能想到的东西,任何人都知道我做错了什么?

这很有效,但必须有一个更简单的方法:

if ((($dtDiffEnd->m!=0) || ($dtDiffEnd->d!=0) || ($dtDiffEnd->y!=0) || ($dtDiffEnd->h!=0) || ($dtDiffEnd->i!=0) || ($dtDiffEnd->s!=0)))

任何建议表示赞赏。

1 个答案:

答案 0 :(得分:0)

$dtDiffStart=$dtStart->diff($dtStGoogle);
$dtDiffEnd=$dtEnd->diff($dtEndGoogle);

是DateInterval的2个实例,所以它总是被认为是真的。

if ($dtStart!=$dtEndGoogle)

在您的情况下,它将始终返回true,因为您的两个DateTime实例不同(不同的时区)

如果您只是想检查$ dtStart和$ dtEndGoogle是否不同,请执行以下操作:

($dtStart->format('U') != $dtEndGoogle->format('U'))

'U'用于获取unix时间戳。您可以根据需要更改格式。

相关问题