Forum Moderators: coopster

Message Too Old, No Replies

calculate dates from start date, number of weeks and specific days

calculate dates from start date, number of weeks and specific days

         

drooh

9:01 pm on Sep 15, 2010 (gmt 0)

10+ Year Member



Original start date is given, say 2010-09-22 (a Wednesday).
Also, the class goes for 4 weeks and is on Mondays and Wednesdays.

How would i calculate the dates based off this info?

Id like to build an array that stores an entry for each date this class happens. So end the end I need to have an array with the following:

2010-09-22
2010-09-27
2010-09-29
2010-10-04
2010-10-06
2010-10-11
2010-10-13
2010-10-18

I've tried looping through a for loop with the counter set to the number of weeks which is 4 but Im not sure exactly what to do. I'm assuming Ill use mktime to add the appropriate number of days to the original starting day but Im not sure how to calculate that.

So my logic goes something like this
Start Date -> Find what day of the week this is -> Find next recurring day and how many days from the last and add that to mktime

drooh

9:24 pm on Sep 15, 2010 (gmt 0)

10+ Year Member



Can someone tell me if this looks like a solution?

$a = array();
// classA every mon wed starts on wed 22nd
$start = '2010-09-22';
$m = 1;
$t = 0;
$w = 1;
$h = 0;
$f = 0;
$s = 0;
$u = 0;
$weeks = 4;

$i = 0;
while($i<$weeks){
if($m){$a[] = array('date' => date('Y-m-d',strtotime($start ." +$i week Mon")));}
if($w){$a[] = array('date' => date('Y-m-d',strtotime($start ." +$i week Wed")));}
$i++;
}

sort($a);

foreach($a as $i){
foreach($i as $item){
echo $item."<br />";
}
}

coopster

10:39 am on Oct 5, 2010 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The "if($m)" and "if($w)" are always going to be true, you initialized the values earlier. You could add one week to each day that is to be shown as you are attempting, or you could review each day itself to see if it is in your desired output. The processing/performance would be better in the prior, here is an example of the latter ...

/** 
* Week days
* 0 = Sunday, 6 = Saturday
*/
$weekDays = array(
0 => false,
1 => true,
2 => false,
3 => true,
4 => false,
5 => false,
6 => false
);
$weeks = 4;
$date = strtotime('2010-09-22');
$i = 0;
$totalDays = $weeks * 7;
while ($i < $totalDays) {
$weekDay = date('w', $date);
if ($weekDays[$weekDay]) {
print date('Y-m-d', $date) . "\n";
}
$date = strtotime('+1 day', $date);
$i++;
}