Chinmay235
Chinmay235

Reputation: 3414

How to get every month second Sunday between two dates?

I have two dates I want to get each month second Sunday between two mentioned date. How to do that in PHP code?

Below my two mentioned date.

$start_date = '2016-08-24';
$end_date = '2017-09-24';

Thank You

Upvotes: 1

Views: 652

Answers (3)

trincot
trincot

Reputation: 350137

You could use the relative formats you can use with the DateTime class, like this:

$start_date = new DateTime('2016-08-24');
$end_date = new DateTime('2017-09-24');

$dt = clone $start_date;
$dt->modify('first day of this month')->modify('+2 Sundays');
while ($dt <= $end_date) {
    if ($dt >= $start_date) $result[] = $dt->format('Y-m-d');
    $dt->modify('first day of next month')->modify('+2 Sundays');
}
print_r ($result);

The output is:

Array
(
    [0] => 2016-09-11
    [1] => 2016-10-09
    [2] => 2016-11-13
    [3] => 2016-12-11
    [4] => 2017-01-08
    [5] => 2017-02-12
    [6] => 2017-03-12
    [7] => 2017-04-09
    [8] => 2017-05-14
    [9] => 2017-06-11
    [10] => 2017-07-09
    [11] => 2017-08-13
    [12] => 2017-09-10
)

Upvotes: 2

Basant Rules
Basant Rules

Reputation: 807

Try This one

    $startdate = '2016-08-24';
   $enddate = '2017-09-24';
    getSundays($startdate,$enddate);
    function getSundays($startdate,$enddate) {
        $startweek=date("W",strtotime($startdate));
        $endweek=date("W",strtotime($enddate));
        $year=date("Y",strtotime($startdate));
        for($i=$startweek;$i<=$endweek;$i++) {
            $result=getWeek($i,$year);
            if($result>$startdate&&$result<$enddate) {
                echo date('Y-m-d', strtotime('second sunday of '.date("F",strtotime($startdate)).' '.$year)).'<br/>';
                //echo " Sunday:"."<br>";
            }
        }
    }
    function getWeek($week, $year) {
      $dto = new DateTime();
      $result = $dto->setISODate($year, $week, 0)->format('Y-m-d');
      return $result;
    }

Upvotes: 0

michail_w
michail_w

Reputation: 4471

Please make use of php classes DateTime and DateInterval. On DateInterval manual page there are examples of code similar to your problem.

Upvotes: 0

Related Questions