How to Loop Between Two Dates in PHPIn programming languages its easy to loop between two numbers or run a foreach over items in array, but what about a loop between two dates?
The problem was simple enough, I wanted to loop over all the days between two dates, taking a new month or year into account and rolling over automatically.
Luckily there is a way loop between two dates in PHP which is actually pretty simple and uses a while loop.
date_default_timezone_set('UTC');
$start_date = '2010-01-01';
$end_date = '2010-03-15';
while (strtotime($start_date) <= strtotime($end_date)) {
echo $start_date . "\n";
$start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
}
You can adjust to +1 days
to +2 days for every other day, or +1 week for every week between two dates.
If you are working with actual DateTime
classes this becomes even easier.
$start_date = new DateTime('2010-01-01');
$end_date = new DateTime('2010-03-15');
$daterange = new DatePeriod($start_date, new DateInterval('P1D'), $end_date);
foreach($daterange as $date){
echo $date->format("Y-m-d") . "\n";
}
The DateInterval
takes in the period to use specified as a string. P is for a date/time period, 1 is the numerical value and D represents Days. You can use W for weeks, M for months, Y for years. P2W would be an interval of 2 weeks. This also works with time. If you want to work with Time periods, specify PT as the staring letters, then you can use H, M or S for hours, minutes and seconds. For example, PT30M would be an interval of 30 minutes. T90M would be 1 hour 30 minutes.
Further examples are two days - P2D. Two seconds - PT2S. Six years and five minutes is P6YT5M.
The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as P1Y4D, not P4D1Y.