Home > Backend Development > PHP Tutorial > How to Retrieve Dates within a Specified Range in PHP?

How to Retrieve Dates within a Specified Range in PHP?

Susan Sarandon
Release: 2024-10-20 22:37:02
Original
667 people have browsed it

How to Retrieve Dates within a Specified Range in PHP?

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);
}
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template