Menu

Get Time Range Between Two Date In Php

Hello Guys,
Today One of my friends ask me a question in PHP, how he can get the time range between two dates or times in PHP? So, I help him to create the function to achieve his goal.
After that, I also decide to create a tutorial blog for everyone. I think this post will be helpful to others like my friends.
So, Without wasting time let's start.
 

Create Php function 

For this, I will use a function. We can do this without function. But as we all know we should use the function to optimize the code and repeat uses.
I will create a function with the name getTimeInterval. 

function getTimeInterval($start,$end) {
	$start_time = new DateTime($start);
	$end_time = new DateTime($end);
	$timerange = [];
	while ($start_time < $end_time) {
		$interval = $start_time->format('h:i A') . "-";
		$start_time->modify('+60 minutes');
		$interval .= $start_time->format('h:i A');
		$timerange[] = $interval;
	}

	return $timerange;
}

This function requires two params, these params need to be DateTime in string format. Which will be used to create a DateTime object in the function. With an object, we can easily modify the DateTime. 
In this $start_time->modify('+60 minutes') line I am adding 1 hour to the start time to get the time after the 1 hour. You can change the value according to your use.
 

Call getTimeInterval function

After creating the function, We can use the function as per our requirement.
 

$range = getTimeInterval('2022-12-08 12:00','2022-12-08 16:00');

echo "
"; print_r($range);

 You can pass any date and time in the function.
Let's check the result.

Output

Array
(
    [0] => 12:00 PM-01:00 PM
    [1] => 01:00 PM-02:00 PM
    [2] => 02:00 PM-03:00 PM
    [3] => 03:00 PM-04:00 PM
)

It's all completed here. Now you can use the array as per your requirement. You can also change the DateTime format as per your need.
I hope this is helpful to you. 
if you have any confusion related to this post. You can comment below. 
Please share the post with your friends and colleague.

Thanks 

795
Search

Ads