1

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

Chinmay235
  • 3,236
  • 8
  • 62
  • 93

3 Answers3

2

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
)
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Great answer, but this didn't work for the year 2019 in July, see https://3v4l.org/MSq19 (the last Sunday in June breaks this). Just a small change and it worked well: Change "last day of previous month" to "first day of this month" and "last day of this month" to "first day of next month", see: https://3v4l.org/7VOPf – cheesetor Mar 18 '19 at 08:00
  • Thank you, @cheesetor, for spotting this. I shamelessly updated the answer based on your comment. Thanks! – trincot Mar 18 '19 at 09:53
0

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

michail_w
  • 4,318
  • 4
  • 26
  • 43
0

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;
    }
Basant Rules
  • 785
  • 11
  • 8