Home  >  Article  >  Backend Development  >  How to Find All Dates Between Two Specified Dates in PHP?

How to Find All Dates Between Two Specified Dates in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-20 22:38:30740browse

How to Find All Dates Between Two Specified Dates in PHP?

Find the Dates Between Two Specified Dates

If you're working with dates and time intervals in your PHP project, a common task is determining the individual dates that fall within a given range. Here's how to tackle this problem:

Consider two dates: 20th April 2010 and 22nd April 2010. To obtain a list of dates between them in the format 20, 21, 22, follow these steps:

  1. Convert String Dates to UNIX Timestamps:
<code class="php">$start = strtotime('20-4-2010');
$end = strtotime('22-4-2010');</code>
  1. Iterate Over the Date Range:
<code class="php">for($current = $start; $current <= $end; $current += 86400) {
    echo date('d', $current);
}

Here, we iterate from the starting timestamp to the ending timestamp, incrementing by one day (86400 seconds) for each iteration. The date() function is used to extract the day from the timestamp.

Alternate Methods:

  • Using a Specific Number of Days:

    <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') // or pass in just the no. of days: 2
    );
    
    foreach ( $period as $dt ) {
    echo $dt->format( 'd-m-Y' );
    }</code>

    The above is the detailed content of How to Find All Dates Between Two Specified 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