views:

54

answers:

4

I am creating a calendar in PHP and in the database have a date, let's say 6-10-10.

Sometimes I have repeating events, stored as weekly repeating, so if the date is 6-10-10, and I am repeating an event every two weeks from that day (including that day) what is the best way to find dates for every two weeks from 6-10-10?

For example, let's say the date is 7-8-10, how can I check to see that date meets my criteria?

+1  A: 

If this is for a calendar, how about building a chain of valid dates using strtotime?

// 10 dates every two weeks starting next thurdsay

$valid_dates = array();
$date_counter = 0;  
$date_counter = strtotime("next thursday"); // I love being a lazy bastard!

while ($i < 10)
 {
   array_push($valid_dates, $date_counter);
   $date_counter = strtotime("+2 weeks", $date_counter); 
   $i++;

 }

foreach ($valid_dates as $date)
 echo date("Y/m/d", $date)."<br>";

Will output:

2010/06/17
2010/07/01
2010/07/15
2010/07/29
2010/08/12
2010/08/26
2010/09/09
2010/09/23
2010/10/07
2010/10/21
Pekka
That assumes that the valid dates end at some point. What if my valid dates go infinitely in the future (like setting a repeating every 2 weeks forever).
kylex
@kylex yes, this is an approach with a given number of dates. The DATEDIFF approach looks easier for this specific task, if that's all you need to do go with that. You may need something like `strftime` based though if it becomes more complex like "every 3rd thursday in the month".
Pekka
+1  A: 

You can use DATEDIFF function.

For example

SELECT * FROM myTable WHERE ( DATEDIFF( myDate,  '2007-12-30' ) % 14 ) = 0
marvin
A: 

Shouldn't result of the DATEDIFF function in MySQL be a multiple of 7 (for events repeating each week), or 14 (for events repeating every two weeks) etc?

Anax
+2  A: 

What's up with the looping?! Discrete Math 101: How do you figure out if a number is even? n%2==0

How do you figure out if a date is (uh...) biweekly? date%2weeks==0

Toss in an offset and you get (date-startdate)%2weeks

$startdate = strtotime("10 June 2010");
$otherdate = strtotime("8 July 2010");
$twoweeks  = strtotime("+2 weeks") - time();
if($otherdate>$startdate && (($otherdate-$startdate)%$twoweeks)==0) {
    // this is n * two weeks after
}
LeguRi
+1, this is the best and shortest solution
Pekka
@Pekka - thanks for not taking my loop jab personally :)
LeguRi
@Richard no problem, you were totally right :) It depends on the use - if you need to generate dates to put into a calendar, you need to build a chain. But that wasn't what the OP was asking for.
Pekka
@Richard turns out I had just slightly mis-adjusted my time machine, and my answer was *really* intended for this question that popped up today: http://stackoverflow.com/questions/3023235/array-of-previous-weeks :)
Pekka