douxing5598 2015-10-27 15:16
浏览 69
已采纳

试图比较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);

I am using PHP 5.6.13 and now 5.6.14 Then I try to compare them and the result is either always true or always false regardless of the value.

  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

Either I get results with values of 0 0 0 0 0 0 (always true) or none (always false) at all and both are incorrect. I have tried other crazy things with the same results.

I have tried everything I can think of, anyone know what I am doing wrong?

This works, but there has got to be a simplier way:

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

any advice appreciated.

  • 写回答

1条回答 默认 最新

  • duanli8577 2015-10-27 16:36
    关注
    $dtDiffStart=$dtStart->diff($dtStGoogle);
    $dtDiffEnd=$dtEnd->diff($dtEndGoogle);
    

    Are 2 instances of DateInterval, so it'll always be considered as true.

    if ($dtStart!=$dtEndGoogle)
    

    In your case it will always return true, as your two DateTime instances are different (different timezone)

    If you just want to check if $dtStart and $dtEndGoogle are different, just do:

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

    'U' is used to get the unix timestamp. You can change the format depending on your needs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!