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.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化