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

报告相同问题?