How to Loop Between Two Dates in PHP

In 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?

By Tim Trott | PHP Tutorials | April 2, 2010

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.

php
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.

php
$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.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.