How to Extract Date Ranges Between Two Dates in PHP?

Barbara Streisand
Release: 2024-10-20 22:43:29
Original
658 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!