Calculate sunday between two dates

I want to calculate all Sunday between two dates. I tried the following code. It works great if there are fewer days, but if I type more days. It continues to process, and the maximum runtime exceeds me, changed the time, but even continues to process even the runtime of 200 seconds.

code

<?php
$one="2013-01-01";
$two="2013-02-30";

$no=0;
for($i=$one;$i<=$two;$i++)
{

    $day=date("N",strtotime($i));
    if($day==7)
    {
    $no++;
    }
}
echo $no;

?>

Please, help.

+5
source share
3 answers

John Conde's answer is correct, but here is a more efficient and matte solution:

$start = new DateTime('2013-01-06');
$end = new DateTime('2013-01-20');
$days = $start->diff($end, true)->days;

$sundays = intval($days / 7) + ($start->format('N') + $days % 7 >= 7);

echo $sundays;

Let me break it for you.

$start = new DateTime('2013-01-06');
$end = new DateTime('2013-01-20');

First, create DateTime objects , which are powerful PHP built-in objects designed specifically for this kind of problem.

$days = $start->diff($end, true)->days;

DateTime:: diff, $start $end ( true , ) .

$sundays = intval($days / 7) + ($start->format('N') + $days % 7 >= 7);

- , . -, , , $days / 7 , int intval.

, ; , - 4 ; - . , , , . :

7 , . , , 1, 0, , int.

! , , , , , . , !

+25
<?php
$no = 0;
$start = new DateTime('2013-01-01');
$end   = new DateTime('2013-04-30');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt)
{
    if ($dt->format('N') == 7)
    {
        $no++;
    }
}
echo $no;

+8

Here is the solution if you want on Sundays in a specific date range.

function dateRange($begin, $end, $interval = null)
{
  $begin = new DateTime($begin);
  $end = new DateTime($end);

  $end = $end->modify('+1 day');
  $interval = new DateInterval($interval ? $interval : 'P1D');

  return iterator_to_array(new DatePeriod($begin, $interval, $end));
}

/* define date range */
$dates = dateRange('2018-03-01', '2018-03-31');

/* define weekdays */
$weekends = array_filter($dates, function ($date) {
  $day = $date->format("N");
  return $day === '6' || $day === '7';
});

/* weekdays output */
foreach ($weekends as $date) {
  echo $date->format("D Y-m-d") . "</br>";
}

/* define sundays */
$sundays = array_filter($dates, function ($date) {
  return $date->format("N") === '7';
});

/* sundays output */
foreach ($sundays as $date) {
echo $date->format("D Y-m-d") . "</br>";
}

/* define mondays */
$mondays = array_filter($dates, function ($date) {
 return $date->format("N") === '1';
});

/* mondays output */
foreach ($mondays as $date) {
echo $date->format("D Y-m-d") . "</br>";
}

Just change the number for any days you want in your output:

Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
Sunday = 7
0
source

All Articles