Paul Atkins
Paul Atkins

Reputation: 355

php datetime class and for loop problem

I was wondering if somebody could help with this problem I have.

I have an array which contains the weekdays in which people want to be contacted. I have then created a for loop which adds 1 day to the current date until the day of the week matches a day in which a person wants to be contacted.

The problem I am having is that the loop always goes one day too far. I am just wondering if this is the best way to accomplish what I am trying to do or is there a better way?

Here is my code:

$ScheduleWindow = array('Monday', 'Tuesday');

$date = new DateTime('today');

$dow = getdate($date->getTimestamp());

for($date, $dow;!in_array($dow['weekday'], $ScheduleWindow);$date->add(new DateInterval('P1D'))){
$dow = getdate($date->getTimestamp());
}

echo "Next date to contact is" . $date->format('Y-m-d H:i:s') . "\n";

The code currently echoes "Next date in schedule window is2011-01-25 00:00:00" however I need it to be the date 2011-01-24.

Thanks for looking.

Upvotes: 0

Views: 537

Answers (2)

urfusion
urfusion

Reputation: 5501

For applying date in a loop you have to increase date according to your condition. So there is a way:

$date = date ("Y-m-d", strtotime ("+1 day", strtotime($date)));

For further code visit http://urfusion.blogspot.com.

Upvotes: 1

deceze
deceze

Reputation: 522016

Your for loop expressed in words does this:

If the weekday in $dow is not within schedule window,  
assign the current date to $dow,
increase the date,
repeat.

You're checking against the un-increased date on the next loop.

Your loop is also much too complicated. This should do just fine:

while (!in_array($dow['weekday'], $ScheduleWindow)) {
    $date->add(new DateInterval('P1D'));
    $dow = getdate($date->getTimestamp());
}

Your DateTime object, getdate, DateInterval operation is much more complex than it needs to be:

$scheduleWindow = array('Monday', 'Tuesday');

$date = new DateTime('today');
while (!in_array($date->format('l'), $scheduleWindow)) {
    $date->add(new DateInterval('P1D'));
}

echo "Next date to contact is " . $date->format('Y-m-d H:i:s');

Upvotes: 1

Related Questions