duanlinghe8417 2014-03-10 18:27
浏览 74
已采纳

使用DateTime diff的DateInterval错误

I'm comparing two DateTime :

//Get the current DateTime
$date_now = new DateTime;
var_dump($date_now); // 2014-03-10 19:04:29

// I need to subtract 12 hours (I'm using $date_past to fetch $db_date in a request)
$date_past = $date_now->sub(new DateInterval("PT12H"));

// Get the DateTime from $db_date just fetched in database
$alert_date = new DateTime($db_date);
var_dump($alert_date); // 2014-03-10 17:04:00 in my test

// Get the difference
$diff = $alert_date->diff($date_now);
var_dump($diff->format("%H:%I:%S")); //09:59:31

So I get 09:59:31 and also $diff->invert == 1 which means that it's a negative value.

I saw this issue : php datetime->diff is calcualting wrong amount of hours (3 too much) and I think it's similar problem but I can't find a solution to keep using ->sub(). Any ideas ?

If you think it could be a TimeZone problem, I checked all my DateTime and they all have a TimeZone set to "Europe/Berlin", so I don't think it come from here.

Thank you !

  • 写回答

1条回答 默认 最新

  • doubi5520 2014-03-10 18:35
    关注

    The problem is that when you assign an object to a variable, it is assigned by reference. So when you do:

    $date_past = $date_now->sub(new DateInterval("PT12H"));
    

    The variables $date_past and $date_now both point to exactly the same reference and when you modify one, you modify both. You will notice this if you simply echo out the variables:

    $date_now = new DateTime;
    $date_past = $date_now->sub(new DateInterval("PT12H"));
    
    echo $date_now->format('c'); // 2014-03-10T00:38:56-06:00
    echo $date_past->format('c'); // 2014-03-10T00:38:56-06:00
    

    Notice how they both print exactly the same thing. Normally what you want to do is use clone:

    $date_past = clone $date_now;
    $date_past->sub(new DateInterval("PT12H"));
    
    echo $date_now->format('c'); // 2014-03-10T12:41:20-06:00
    echo $date_past->format('c'); // 2014-03-10T00:41:20-06:00
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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