我希望在给定日期的下一个双周(每2周)会议中用PHP进行计算。
所以鉴于第一次会议是在2015年12月1日,并且每两周举行一次,从给定日期开始的下一次会议的日期是什么时候?
我认为显而易见的答案是:
$start = new DateTime('2015-12-01'); // Meeting origination date
$target = new DateTime('2016-03-10'); // The given date
$targetPlus = clone $target; // Could use DateTimeImmutable for $target (PHP>=5.5)
$targetPlus->modify("+3 weeks"); // Get a date *past* the next possible meeting
$interval = new DateInterval("P2W"); // Create a 2 week interval
$period = new DatePeriod($start, $interval, $targetPlus); // Get all dates from orig to target+2weeks
foreach ($period as $date) { // Look at all dates in the Period
if ($date > $target) { // find first > target
print("Next meeting is: " . $date->format('D, d M Y') . "\n");
break;
}
}
但是想知道是否有一种方法可以通过所有可能的会议循环到指定的日期(然后是一些)。
答案 0 :(得分:1)
是的,有更明确的方法,你可以用这段代码计算新会议的日期$targetMeeting
:
<?php
date_default_timezone_set('America/Los_Angeles');
$start = new DateTime('2015-12-01'); // Meeting origination date
$target = new DateTime('2016-03-10'); // The given date
$targetPlus = clone $target; // Could use DateTimeImmutable for $target (PHP>=5.5)
$targetPlus->modify("+3 weeks"); // Get a date *past* the next possible meeting
$interval = new DateInterval("P2W"); // Create a 2 week interval
/* -- Begin of new code --*/
$targetMeeting = clone $target;
$intervalBetweenTargetAndStart = $target->diff($start);
$daysBeforeMeeting = 14 - $intervalBetweenTargetAndStart->days % 14;
$targetMeeting->modify("+".$daysBeforeMeeting." days");
print("Next meeting is: " . $targetMeeting->format('D, d M Y') . "\n");
/* -- End of new code --*/
$period = new DatePeriod($start, $interval, $targetPlus); // Get all dates from orig to target+2weeks
foreach ($period as $date) { // Look at all dates in the Period
if ($date > $target) { // find first > target
print("Next meeting is: " . $date->format('D, d M Y') . "\n");
break;
}
}
输出:
Next meeting is: Tue, 22 Mar 2016
Next meeting is: Tue, 22 Mar 2016
答案 1 :(得分:0)
尝试计算日期之间的差异,查找事件之间的下一个天数(在您的情况下为14),并将该天数添加到开始日期,如下所示:
<?php
$daysBetween = 14;
$start = new DateTime('2015-12-01'); // Meeting origination date
$target = new DateTime('2016-03-10'); // The given date
$daysApart = $start->diff($target)->days;
$nextMultipleOfDaysBetweenAfterDaysApart = ceil($daysApart/$daysBetween) * $daysBetween;
$dateOfNextMeeting = $start->modify('+' . $nextMultipleOfDaysBetweenAfterDaysApart . 'days');
var_dump($dateOfNextMeeting);
?>