简体   繁体   中英

Date time difference miss to calculate the days to hour

I have a date time difference-

I need to calculate those days also into hour.

$start = '2016-05-26 19:05:00';
$end = '2016-05-29 17:05:00';
$datetime1 = new DateTime($start);
$datetime2 = new DateTime($end);
$interval = $datetime1->diff($datetime2);
echo $interval->format("%h Hours %i Min %s Sec"); //22 Hours 0 Min 0 Sec

I know this:

echo $interval->format('%d days');

I try this:

echo $interval->format("(%h + %d * 24) Hours %i Min %s Sec"); //(22 + 8 * 24) Hours 0 Min 0 Sec
$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';                        
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
echo (($since_start->days)*24)+$since_start->h.' Total Hours<br>';

Use this claculate the days and then multiple by 24 plus remaining hours

Its simple, all though it cannot be done automatically for you, you have to write code.

Here is all you need:

$start = '2016-05-26 19:05:00';
$end = '2016-05-29 17:05:00';
$datetime1 = new DateTime($start);
$datetime2 = new DateTime($end);
$interval = $datetime1->diff($datetime2);

// Below this line is where the magic takes place:

$hourDiff = ($interval->d*24)+($interval->h); //here we calculate the hours

echo $hourDiff //prints 77 because 2 days*24 hours each + 22 hours = 77

In my example I also take into account the years and months (y and m respectively) but you can delete those if you don't want them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM