$begin = new DateTime('2016-01-01');
$end = new DateTime('2016-12-31');
$interval = new DateInterval('P14D');
$datePeriod = new DatePeriod($begin, $interval ,$end);
$givenDate = new DateTime('2016-01-17');
foreach ($datePeriod as $date) {
if ($date < $givenDate) {
continue;
}
echo 'The next recurring period date is ' . $date->format('Y-m-d');
break;
}
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
//Get difference in days
$datediff = $now - $your_date; // in days say 60 days
//use mod with your reoccurring period
$remain = $datediff % $recPeriod // her say 2 weeks = 14 days recurring gets you 4
//nearest recured date
$recdate = strtotime("-".$remain." day", $now); // 4 days ago
Modify similar way for next date too
0
而不是循环,你可以只做一些数学并利用DateTime类:
$start = new DateTime("2016-01-01");
$interval = 14;
$current = new DateTime("2016-01-17");
// Here we subtract from the interval (14 days) the amount of days remaining
// to the next recurring date
$daysUntilNext = $interval - ($current->diff($start)->days % $interval);
$next = $current->modify("+$daysUntilNext days");
// $next now contains the next recurring date
<?php
$start = new DateTime('2016-01-01');
$cutOff = new DateTime('2016-01-17');
$period = new DateInterval('P2W');
// Find out the total number of complete periods between the two dates
$distance = $start->diff($cutOff)->days;
$periodsBetween = (int) ($distance / $period->d);
// Then add on that number of periods + 1 to the original date
for ($a=1; $a<=$periodsBetween + 1; $a++)
{
$start->add($period);
}
echo $start->format('Y-m-d'); // 2016-01-29
6 回答
您可以使用DatePeriod来完成它:
输出将是:
如果你是开放的,不介意数据库选项和迷你cron脚本,我有一个建议 . 创建一个名为recurring_track的表,并具有键值列:
例如:
last_recurring_period作为键和值为05-25-2016
现在运行一个cron脚本,只在每次重复出现持续时间时更新它 .
现在,您只需要查询此表以确定最后一个周期时间,以及现在何时将是您可以添加和确定的给定日期的下一个周期 .
试试这个,
而不是循环,你可以只做一些数学并利用DateTime类:
另一种看法,与@Matei Mihai的相似,但不需要在最后一个循环中进行检查 . 感觉应该有一个更好的方法来添加DateInterval的多个实例到DateTime .