Resolving DateTime Difference in PHP

2019-07-10 04:22发布

问题:

I am running into some issues when trying to find the difference between two dates. As an example I have date1 as 2015-09-14 and date2 as 2015-09-18. The difference would be 5 days, however the code is returning 4 days. Below is the code:

$datetime1 = new DateTime($startdate);
$datetime2 = new DateTime($enddate);
$interval = $datetime1->diff($datetime2);
$ptohours = $interval->format('%d %H');

where startdate is 2015-09-14 07:00:00 and enddate is 2015-09-14 16:00:00.

I am trying to calculate the hours an employee is requesting as PTO. In the above example it should give 45 hours.

回答1:

Given these inputs:

$startdate = '2015-09-14 07:00:00';
$enddate = '2015-09-18 16:00:00';

$datetime1 = new DateTime($startdate);
$datetime2 = new DateTime($enddate);
$interval = $datetime1->diff($datetime2);
$ptohours = $interval->format('%d %H');

print_r($interval);

Output is four days:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 4
    [h] => 9
    [i] => 0
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 4
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

Why?

Let's map out in twenty-four-hour intervals:

-14 07:00
    a day has passed 1
-15 07:00
    that's a day 2
-16 07:00
    that's another day 3
-17 07:00
    that's one more day 4
-18 07:00
    not yet a full day
-18 16:00

So the result of four days is technically correct.

If you think you should be getting five days, then you might consider applying a formula like this:

$adjustedDays = ceil($interval->d + $interval->h / 24.0);

Which will give you what you're looking for.