How to Get All Dates Between Two Dates in PHP

Introduction

Sometimes while developing applications with historical data, we may be required to get all dates between 2 specific dates. I came across a similar situation while building an application related to cryptocurrency assets management.

I had to get the price of all cryptocurrencies for the past 4 years. I was using PHP with Laravel. In this article, I will share some ideas on how to get the list of dates between 2 dates with PHP. The logic is straight forward and you may find it useful.

Step 1 - Define the Function Parameters

The function will take 2 parameters, the starting date, and the ending date, The function will return an array of dates between them.

When the ending date is set as null, the function should return all dates from the starting date till now.

function getAllDatesBetween($startDateStr=null, $endDateStr=null)

Step 2 - Function to Get the List of Dates Between Two Dates

This example function to get the list of all dates between two dates used the strtotime function along with the step variable to get the next day in a while loop.

private function getAllDatesBetween($startDateStr, $endDateStr=null)
{
	$dates = [];
    if ($endDateStr == null){
		$endDate = date('d-m-Y');
	}
	else {
		$endDate = date($endDateStr);
	}
	$stepVal = '+1 day';
	while(strtotime($startDate) <= strtotime($endDate)){
		$dates[] = $startDate;
		$startDate = date('d-m-Y' ,strtotime($stepVal, strtotime($startDate)));
	}
	return $dates;
}

Sample Invocations

Passing a start date and an end date.

getAllDatesBetween('01-01-2017', '06-01-2017');
Output:
[01-01-2017, 02-01-2017, 03-01-2017, 04-01-2017, 05-01-2017, 06-01-2017]

Passing only the start date, the function will return all dates from the start date till today.

getAllDatesBetween('01-08-2021');
Output:
[01-08-2021, 02-08-2021, 03-08-2021, 04-08-2021]

The current date was 4th August 2021 and hence the result had dates till 4th August.

Conclusion

Though this is not a very common use case, the function will be helpful while developing applications handling historical data like stocks and other investment assets.

The function parameters and return values can be altered to any format of your choice.

Vipin

Vipin

I am a dreamer. I admire the web. I admire anything about the web.