Obtaining Dates within a Specified Range
When presented with two specific dates, such as 20-4-2010 and 22-4-2010, a common programming task is to retrieve the intervening dates in a concise format, such as 20, 21, and 22. To achieve this, we can leverage various approaches in PHP.
Solution 1: Looping with strtotime and date
This involves using the strtotime() function to convert the dates to timestamps and then iterating through the range using a for loop. The date() function is used to format the timestamps as dates:
<code class="php">$start = strtotime('20-04-2010'); $end = strtotime('22-04-2010'); for ($current = $start; $current <= $end; $current += 86400) { echo date('d', $current); }
Solution 2: Looping with DateInterval and DateTime (PHP 5.3 )
PHP 5.3 and later offers a more concise and elegant solution using the DateInterval and DateTime classes:
<code class="php">$period = new DatePeriod( new DateTime('20-04-2010'), DateInterval::createFromDateString('+1 day'), new DateTime('23-04-2010') ); foreach ($period as $dt) { echo $dt->format('d'); }</code>
The above is the detailed content of How to Retrieve Dates within a Specified Range in PHP?. For more information, please follow other related articles on the PHP Chinese website!