PHP Select every other Wednesday

前端 未结 4 1731
天命终不由人
天命终不由人 2021-01-27 01:18

I need help Select every other Wednesday starting on 5/2/12. This code below selects every other Wednesday starting on the week it currently is. But i need to set the beginning

相关标签:
4条回答
  • 2021-01-27 02:08

    Give it a date in the string, instead of "Wednesday" (that chooses the next Wednesday), write:

    strtotime('20120502 +' . ($i * 2) . ' weeks'))

    To choose that date. (Format is yyyymmdd).

    0 讨论(0)
  • 2021-01-27 02:14

    Use mktime to create your starting date and pass that as the second argument to strtotime so that counting starts from there:

    $startDate = mktime(0, 0, 0, 5, 2, 2012); // May 2, 2012
    for ($i = 0; $i < $number_of_dates; $i++) {
       $date = strtotime('Wednesday +' . ($i * 2) . ' weeks', $startDate);
       echo date('m-d-Y', $date). "<br>".PHP_EOL;
    }
    

    See it in action.

    0 讨论(0)
  • 2021-01-27 02:19

    If you have PHP 5.2.0 or newer, you can do it easily this way:

    $date = new DateTime('2006-05-02');
    for ($i=0; $i<10; $i++) {
       echo $date->format('m-d-Y').'<br/>'.PHP_EOL;
       $date->modify('+1 week');
    }
    
    0 讨论(0)
  • 2021-01-27 02:20

    You could also use the DatePeriod and DateInterval classes to make life easier.

    Standard disclaimer: both of the classes above require PHP >= 5.3.0.

    $number_of_dates = 10;
    
    $start_date = new DateTime("5/2/12");
    $interval   = DateInterval::createFromDateString("second wednesday");
    $period     = new DatePeriod($start_date, $interval, $number_of_dates - 1);
    
    foreach ($period as $date) {
        echo $date->format("m-d-Y") . "<br>" . PHP_EOL;
    }
    
    0 讨论(0)
提交回复
热议问题