Kin
Kin

Reputation: 4596

How to iterate day in php?

I need to get the next 7 (or more) dates except sunday. Firstly i did it like

$end_date = new DateTime();
$end_date->add(new DateInterval('P7D'));

$period = new DatePeriod(
    new DateTime(),
    new DateInterval('P1D'),
    $end_date
);

And after checked $period in foreach. But then i noticed that if i remove Sunday i need to add one more day to the end and this is each time when Sunday is... Is there any way to do it?

Upvotes: 3

Views: 1568

Answers (4)

John Conde
John Conde

Reputation: 219804

$start = new DateTime('');
$end = new DateTime('+7 days');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    if ($dt->format("N") === 7) {
        $end->add(new DateInterval('P1D'));
    }
    else  {
        echo $dt->format("l Y-m-d") . PHP_EOL;
    }
}

See it in action

Upvotes: 4

salathe
salathe

Reputation: 51950

I'm a fan of using iterators, to keep the actual loop as simple as possible.

$days_wanted = 7;

$base_period = new DatePeriod(
    new DateTime(),
    new DateInterval('P1D'),
    ceil($days_wanted * (8 / 7)) // Enough recurrences to exclude Sundays
);

// PHP >= 5.4.0 (lower versions can have their own FilterIterator here)
$no_sundays = new CallbackFilterIterator(
    new IteratorIterator($base_period),
    function ($date) {
        return $date->format('D') !== 'Sun';
    }
);

$period_without_sundays = new LimitIterator($no_sundays, 0, $days_wanted);

foreach ($period_without_sundays as $day) {
    echo $day->format('D Y-m-d') . PHP_EOL;
}

Upvotes: 1

Martin Perry
Martin Perry

Reputation: 9527

You can try using UNIX time, adding day and if day is Sunday, add another one. First day of your list will be eg. today at 12:00. Than you add 24 * 60 * 60 to get next day, and so on. Convert UNIX to day is simple, use date() function.

$actDay = time();
$daysCount = 0;
while(true)
{
   if (date("D", $actDay) != "Sun") 
   {
     //do something with day
     $daysCount++;
   }

   if ($daysCount >= LIMIT) break;

   $actDay += 24 * 60 * 60;
}

Upvotes: 0

Jon
Jon

Reputation: 437336

You cannot remove days from a DatePeriod, but you can simply keep a count of non-Sundays and keep iterating until you have accumulated 7 of them:

$date = new DateTime();

for ($days = 0; $days < 7; $date->modify('+1 day')) {
    if ($date->format('w') == 0) {
        // it's a Sunday, skip it
        continue;
    }

    ++$days;
    echo $date->format('Y-m-d')."\n";
}

Upvotes: 0

Related Questions