drhqkz3455 2017-09-02 04:37
浏览 36
已采纳

以小数格式表示的2个日期时间之间的差异

I have 2 DateTimes, I need to calculate the difference between them in hours in decimal format. The hard part is making sure the result is storing the value to 2 decimal places.

$datetime1 = new DateTime("2017-09-01 23:00:00");
$datetime2 = new DateTime();
$difference = $datetime2->diff($datetime1);

But the result is just a whole number which loses too much accuracy for me. How to keep the value to 2 decimal places?

  • 写回答

2条回答 默认 最新

  • dsa111111 2017-09-02 05:55
    关注

    DateTime::diff returns DaterInterval that has a whole number for each individual time related property.

    The days property does not account for increments less than a day, as they are accumulated to and removed from the lesser properties and then is rounded down.

    So $diff->h will never be greater than 23. While $diff->s and $diff->i will never be greater than 59. Where days will contain the total days within the year and month properties. Not to be confused with $diff->d, which is the incremental number of days.

    In order to determine the total hours using diff, you just need to perform math on each of the properties to retrieve the number of hours of the property.

    Demonstration: https://3v4l.org/KhBQC

    $datetime1 = new DateTime('2017-09-01 23:00:00');
    $datetime2 = new DateTime('2017-09-02 01:34:00');
    $diff = $datetime2->diff($datetime1);
    $hours = round($diff->s / 3600 + $diff->i / 60 + $diff->h + $diff->days * 24, 2);
    echo $hours; //2.57
    

    In php 7.1 you can also account for microseconds by adding $diff->f / 3.6e+9.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题