问题
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:
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
}
回答2:
You can use DATEDIFF function.
For example
SELECT * FROM myTable WHERE ( DATEDIFF( myDate, '2007-12-30' ) % 14 ) = 0
回答3:
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
回答4:
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?
来源:https://stackoverflow.com/questions/3018824/check-for-repeating-dates