2

I have a calendar that I want to allow events to be repeated on a week day of the month. Some examples would be:

  • Repeat every 4th Tuesday of the month
  • Repeat every 2nd Friday of the month
  • And so on...

What I need is the ability to find out how many week days (for example Tuesday's) have passed this month so far.

I found some code that returns how many Monday's have passed.

$now=time() + 86400;
if (($dow = date('w', $now)) == 0) $dow = 7; 
$begin = $now - (86400 * ($dow-1));

echo "Mondays: ".ceil(date('d', $begin) / 7)."<br/>";

This works well but how do I make it so that I can determine any week day? I cannot seem to get my head around the code to make this work.

Community
  • 1
  • 1
Ben Sinclair
  • 3,896
  • 7
  • 54
  • 94
  • 1
    I would just find the first occurrence of the weekday you need [by looping since the first of the month, till the 7th in the worst case], then just add `7*(n-1)` days to find out the `n-th`. – moonwave99 May 23 '13 at 00:04
  • "I cannot seem to get my head around the code to make this work." --- that's because trivial code should be written from the scratch – zerkms May 23 '13 at 00:04
  • 2
    Check out [this answer](http://stackoverflow.com/a/5381021/642196). – Sean Powell May 23 '13 at 00:05

2 Answers2

1

strtotime is really useful for this kind of thing. Here are lists of the supported syntax. Using your example of repeat every 2nd Friday of the month I wrote the following simple snippet for you:

<?php
    $noOfMonthsFromNow=12;
    $dayCondition="Second Friday of";

    $months = array();
    $years = array();
    $currentMonth = (int)date('m');
    for($i = $currentMonth; $i < $currentMonth+$noOfMonthsFromNow; $i++) {
        $months[] = date('F', mktime(0, 0, 0, $i, 1));
        $years[] = date('Y', mktime(0, 0, 0, $i, 1));
    }
    for ($i=0;$i<count($months);$i++){
        $d = date_create($dayCondition.' '.$months[$i].' '.$years[$i]); 
        if($d instanceof DateTime) echo $d->format('l F d Y H:i:s').'<br>';
    }
?>

This can be tested at: http://www.phpfiddle.org/lite/

C.O.
  • 2,281
  • 6
  • 28
  • 51
  • Yep, that's what I needed. [This answer](http://stackoverflow.com/questions/5380410/repeating-events-on-the-nth-weekday-of-every-month/5381021#5381021) was also helpful. Thanks for your help! – Ben Sinclair May 23 '13 at 01:12
0
$beginningOfMonth = strtotime(date('Y-m-01')); // this will give you the timestamp of the beginning of the month
$numTuesdaysPassed = 0;
for ($i = 0; $i <= date('d'); $i ++) { // 'd' == current day of month might need to change to = from <= depending on your needs
    if (date('w', $beginningOfMonth + 3600 * $i) == 2) $numTuesdaysPassed ++; // 3600 being seconds in a day, 2 being tuesday from the 'w' (sunday == 0)
}

Not sure if this will work, and there's probably a better way to do it; don't have the means to test it right now but hopefully this puts you on the right track! (I get tripped up on date math a bit too, especially with timezones)