tags:

views:

56

answers:

1

I'm trying to figure out the best way to do the following:

If a user chooses a certain day, say June 21, 2010 we will repeat an event every 3rd monday of every month, but if they choose June 28, 2010 the event will repeat every last monday of every month. This is how google calendar does it, and I'm trying to repeat that functionality.

So basically I see it working something like this: Given a date, get the week it exists in, and the day it is on. (1st week, 2nd week, 3rd week, 4th week, and last week.) Obviously sometimes 4th week will be the last week, and if that is the case I'd like to default to last week.

so in psuedocode:

$repeatweek = getweeknumber($date);
$repeatday = date('l', strtotime($date));


$todaysweek = getweeknumber($todaysdate);
$todayday =  date('l', strtotime($todaysdate));

if($todayday == $repeatday && $repeatweek == $todaysweek){
    echo "This is the day";
}

So the trick I guess is to properly define the getweeknumber() function, which I'm having a heck of time with. Especially determining first and last weeks.

A: 

Take a look at the DatePeriod class.

Example:

<?php
$start = new DateTime("June 21, 2010");
$end = new DateTime("December 31, 2010");

$interval = DateInterval::createFromDateString('fourth monday of next month');
$period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE);

foreach ($period as $p) {
    echo $p->format("Y-m-d"), "\n";
}

gives

2010-07-26
2010-08-23
2010-09-27
2010-10-25
2010-11-22
2010-12-27
Artefacto
that looks promising, but I guess the issue would be how do I take a given date, and print on the string "fouth monday of next month" The documentation on DateInterval is pretty sparse.
kylex
The part "monday" is easy to get – just do `$start->format("l")`. For the first, second, etc., the best way would probably be to loop in one-week intervals to see how many mondays are in the month before and next. The documentation for the intervals is here: http://www.php.net/manual/en/datetime.formats.relative.php
Artefacto
hmm, also i'm stuck using php 5.2.x, these features only work on 5.3.x
kylex