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条)

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题