I have to count the hours between two datetimes in php. These two datetimes are coming with minutes and also seconds but they can be ignored. The goal is get the sum of hours. This is sum represents a gap where problem occurs.
Some piece of code you can find down this writing. I have to know the following:
- do i have it done right - or are there some problem using functions like date->diff (like some months do have 30 days while others have 31 days, or problem with leap years?)
- is there a more simplier way to get the sum of hours by date->diff?
To achieve this goal i have done this by:
//delete minutes and seconds from datetime object
$datetime_start = date("Y-m-d h", strtotime($datetime_start));
$datetime_end = date("Y-m-d h", strtotime($datetime_end));
$datetime_start = $datetime_start.":00:00";
$datetime_end = $datetime_end.":00:00";
//create DateTime object
$datetime_start = new DateTime($datetime_start);
$datetime_end = new DateTime($datetime_end);
//get interval between two dates and fill array
$interval = $datetime_end->diff($datetime_start);
$details = array_intersect_key((array)$interval,array_flip(['y','m','d','h','i','s']));
$sum_of_hours = 0;
if(!empty($details["y"])){
$sum_of_hours = $sum_of_hours + $details["y"] * 365 * 24;
};
if(!empty($details["m"])){
$sum_of_hours = $sum_of_hours + $details["m"] * 30 * 24;
};
if(!empty($details["d"])){
$sum_of_hours = $sum_of_hours + $details["d"] * 24;
};
if(!empty($details["h"])){
$sum_of_hours = $sum_of_hours + $details["h"];
};
Example: Between these dates "2018-06-30 02:00:05" and "2018-07-01 05:00:10" i have an interval of 1 day and 3 hours resulting in 27hours.
thx for helping