Home  >  Article  >  Backend Development  >  How to Extract Date Ranges Between Two Dates in PHP?

How to Extract Date Ranges Between Two Dates in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 22:43:29658browse

How to Extract Date Ranges Between Two Dates in PHP?

Getting Dates Between Two Specified Dates in PHP

Given two dates in text boxes (e.g., "20-4-2010" and "22-4-2010"), the goal is to extract the dates between them and format them as "20, 21, 22."

PHP Solution:

To achieve this, utilize the following PHP code:

<code class="php">$start = strtotime('20-04-2010 10:00');
$end = strtotime('22-04-2010 10:00');
for ($current = $start; $current <= $end; $current += 86400) {
    echo date('d-m-Y', $current);
}

Explanation:

  • strtotime() converts the dates to Unix timestamps with a specific time component to prevent time zone issues.
  • The for loop iterates through the timestamps, incrementing by one day (86400 seconds).
  • date() formats each timestamp as a date in the desired format.

Additional Options:

  • Specify the number of days instead of using the end date:
<code class="php">for ($i = 0; $i <= 2; $i++) {
    echo date('d-m-Y', strtotime("20-04-2010 +$i days"));
}
  • Using PHP 5.3's DatePeriod class:
<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-m-Y');
}</code>

The above is the detailed content of How to Extract Date Ranges Between Two Dates in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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