dongtuhe0506 2018-03-08 19:03
浏览 110
已采纳

DateTime diff返回错误的值

I would like to return the number of days between NOW and some datetime using DateTime object. My dates are:

$now = "2018-03-08 14:00:00";
$last = "2018-02-06 20:00:00"; 

And I do it like this:

$now = new DateTime();
$last_dt = new DateTime($last);
$difference = $last_dt->diff($now);

$difference->format('%d');

$num_of_days = $difference->d;

For some weird reason, the value of $num_of_days is 1 (instead of like 30)

Anybody knows why please?

Thank you

  • 写回答

1条回答 默认 最新

  • duanke0178 2018-03-08 19:04
    关注

    You need to use DateInterval::$days to get the total in days.

    DateInterval::$d is just the number of days but in "grouping form", i.e. 32 days difference will return 2 for DateInterval::$d and 1 for DateInterval::$m.

    $last = "2018-04-10 20:00:00"; 
    
    $now = new DateTime();
    $last_dt = new DateTime($last);
    $difference = $last_dt->diff($now);
    
    echo "Difference: ".$difference->m." months and ".$difference->d." days, or ".$difference->days." days in total";
    

    Result

    Difference: 1 months and 2 days, or 33 days in total

    Demo

    You can see more in the manual

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

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services