PHP: days/hours between two dates/datetimes

Use simple PHP functions to calculate time difference between two dates or datetimes. In last code snippet I’ll show how to retrieve list of all days in given interval.

Count days between two dates

function countDaysBetween($start, $end) {
	return (strtotime($end)-strtotime($start))/86400 + 1;
}

echo countDaysBetween('2017-02-26', '2017-03-02'); // will output: 5

Note that I add 1 day at the end. In this case I count days including last one.

86400 – seconds in one day (24 * 60 * 60). So to count hours instead of days you can use (strtotime($end)-strtotime($start))/3600.

Count days between two datetimes

This is interesting because you can have 2 different tasks – count full days ( 24 hours) or not. Only difference is to use round() or ceil() function.
If you want to count full days, you will use:

function countDaysBetween($start, $end) {
	return floor((strtotime($end)-strtotime($start))/86400);
}

echo countDaysBetween('2017-02-26 12:00:00', '2017-02-28 01:00:00'); // will output: 1

In this case there are 1.54 days in given interval but floor() will return 1.
Otherwise you will use:

function countDaysBetween($start, $end) {
	return ceil((strtotime($end)-strtotime($start))/86400);
}

echo countDaysBetween('2017-02-26 12:00:00', '2017-02-28 01:00:00'); // will output: 2

Count hours between two datetimes

function countHoursBetween($start, $end) {
	return round((strtotime($end)-strtotime($start))/3600);
}

echo countHoursBetween('2017-03-01 15:00:00', '2017-03-01 15:01:00'); // output: 0
echo countHoursBetween('2017-03-01 15:00:00', '2017-03-01 16:51:00'); // output: 2
echo countHoursBetween('2017-03-01 15:00:00', '2017-03-02 16:51:00'); // output: 26

In this example I use round() function. So 0.016 hours will be 0 hours and 1.85 hours will be converted as 2 hours.

Get all days between two dates

To get list of days in given time interval, use:

function daysBetween($start, $end) {
	$arr = array();
	$start = strtotime($start);
	$end = strtotime($end);
	while ($start <= $end) {
		$arr []= date('Y-m-d', $start);
		$start = strtotime("+ 1 day", $start);
	}
	return $arr;
}

$days = daysBetween('2017-02-26', '2017-03-02');
print_r($days);

Deprecated: Non-static method dc_jqslicksocial::footer() should not be called statically in /var/www/digitalette.com/wp-includes/class-wp-hook.php on line 298

Notice: Undefined index: show_post in /var/www/digitalette.com/wp-content/plugins/slick-social-share-buttons/inc/dcwp_social.php on line 805