How to get all dates between two given dates in PHP ?
Recently i needed date string array for a project i am working on. Let me show you how i implemented that.
After some digging on PHP documentation. I found there’s a special PHP class DatePeriod that can be used to implement that.
Photo by Alex Jones on Unsplash
“A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.”
DatePeriod class has a signature as below,
public DatePeriod::__construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
As you can can notice, to create DatePeriod object you need two DateTime( Implements DateTimeInterface) objects and DateInterval object .
You can simply create DateTime object by passing date string as below,
public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
$date = new DateTime('2018-01-01'); $date = new DateTime();//now
To create a DateInterval object you need to pass interval string as described below.
public DateInterval::__construct ( string $interval_spec )
$Duration = new DateInterval( "P1M" );
$interval_spec is defined as below,
Period Designator | Description |
---|---|
P | Period |
Y | years |
M | months |
D | days |
W | weeks. These get converted into days, so can not be combined with D. |
T | Time |
H | hours |
M | minutes |
S | seconds |
Below is some samples for interval specifications
String | |
---|---|
P1Y | 1 Year |
P2M | 2 Months |
P7D | 7 Days |
P3W | 3 Weeks |
PT5H | 5 Hours |
PT2H30M | 2 Hour and 30 minutes |
PT5M45S | 5 Minutes 45 seconds |
P3WT8H | 3 weeks 8 hours |
P1Y2M3DT4H5M6S | 1 year 2 months 3 days 4 hours 5 minutes and 6 seconds |
Now you must have basic understanding about DateTime and DateInterval objects. Let’s create a DatePeriod.
$start = new DateTime( '2018-01-01' ); $end = new DateTime( '2018-04-01' ); $interval = new DateInterval('P1D');//one day interval $date_period = new DatePeriod($start, $interval ,$end);
Now you can iterate through the DatePeriod object and create a dates array or use it as you needed
$dates_arr = array(); foreach($date_period as $date){ array_push($dates_arr,$date->format("Y-m-d")); } print_r($dates_arr);
here i have used Format to get the Date in the format i needed.
Let me know your thoughts in comments. Cheers !