Find week days date from range of the two dates

前端 未结 9 1808
执念已碎
执念已碎 2020-12-24 09:03
$start_date = "2013-05-01";
$last_date = "2013-08-30";

How can I get dates of tuesdays and thursdays between these two dates?

相关标签:
9条回答
  • 2020-12-24 10:01
    $start_date = strtotime("2013-05-01");
    $last_date = strtotime("2013-08-30");
    while ($start_date <= $last_date) {
        $start_date = strtotime('+1 day', $start_date);
        if (date('N',$start_date) == 2 || date('N',$start_date) == 4){
            echo date('Y-m-d', $start_date).PHP_EOL;
        }
    }
    
    0 讨论(0)
  • 2020-12-24 10:03

    Try with this

    $startDate = strtotime($start_date);
    $endDate = strtotime($last_date);
    while ($startDate < $endDate) {
        echo date('Y-m-d', $startDate ). "\n";
        // Give the condition to find last Tuesday
        $startDate = strtotime( 'next Tuesday', $startDate );
    }
    
    0 讨论(0)
  • 2020-12-24 10:06
    <?php
    $start    = new DateTime('2013-05-01');
    $end      = new DateTime('2013-08-30');
    $interval = DateInterval::createFromDateString('1 day');
    $period   = new DatePeriod($start, $interval, $end);
    
    foreach ($period as $dt) {
        if ($dt->format("N") == 2 || $dt->format("N") == 4) {
            echo $dt->format("l Y-m-d") . "<br>\n";
        }
    }
    

    See it in action

    What this code does:

    1. Creates a starting date object using DateTime.
    2. Creates a starting date object using DateTime.
    3. Creates a DateInterval object to represent our interval of time to iterate through. In this case 1 day.
    4. Creates a DatePeriod object to manage these objects.
    5. Using DatePeriod, it iterates through the date starting with the starting date and ending at the end date. We use DateTime::format() with the N parameter to get the day number of the week. If the day number of the week is 2 (Tuesday) or 4 (Thursday) echo out it's value.
    0 讨论(0)
提交回复
热议问题