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

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

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下