简体   繁体   中英

PHP Get recurring dates for specific weekday

How to get all recurring dates for chosen week of the day?

For example, today is Wednesday 15/02/2017 and if I choose Thursday how to get next 5 dates starting next Thursday like:

$dates = array(
[0] => "16/02/2017",
[1] => "23/02/2017",
[2] => "02/03/2017",
[3] => "09/03/2017",
[4] => "16/03/2017");

If I choose Tuesday, get dates starting 21/02/2017, which is next Tuesday

You can use strtotime to generate timestamps for this dates, the date function can generate actual dates.

<?php

    // Array for dates
    $dates = [];

    // Get next thursday
    $date = strtotime('thursday');
    $dates[] = $date;

    // Get the next four
    for ($i = 0; $i < 4; $i++)
    {
        $date = strtotime('+1 week', $date);
        $dates[] = $date;
    }

    // Echo dates
    foreach ($dates as $date)
        echo date('Y-m-d', $date);

Take a look at this post

Using that idea:

//Get First Thursday
$date = new DateTime();
$date->modify('next thursday');

echo "<br/>Starting Thursday: " . $date->format('d/m/Y');

//Loop over next 4 Thursdays
for($i = 2; $i <= 5; $i++)
{
    $date->modify('+7 days');
    echo "<br/>Thursday " . $i . ": " . $date->format('d/m/Y');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM