kylex
kylex

Reputation: 14406

Check for repeating dates

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?

Upvotes: 1

Views: 954

Answers (4)

Pekka
Pekka

Reputation: 449395

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

Upvotes: 1

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

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
}

Upvotes: 3

Anax
Anax

Reputation: 9372

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?

Upvotes: 0

ahmetunal
ahmetunal

Reputation: 3950

You can use DATEDIFF function.

For example

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

Upvotes: 1

Related Questions