我将如何构建条件以仅在早上 08:30 到晚上 18:30 之间的日期添加两个小时,不包括周六和周日?
如果给出了一个接近边界的时间(例如周二的 17:30),则剩余的时间应该添加到下一个“有效”时间段的开头。
例如:如果给定的日期是星期二的 17:30,则两个小时相加将导致星期三的 9:30(17:30 + 1 小时 = 18:30、8:30 + 剩余的 1 小时 = 9: 30)。或者,如果给定的日期是星期五的 17:00,则结果将是星期一的 9:00(星期五 17:00 + 1.5 小时 = 18:30、星期一 8:30 + 剩余的 0.5 小时 = 9:00)
我知道如何简单地添加两个小时,如下所示:
$idate1 = strtotime($_POST['date']);
$time1 = date('Y-m-d G:i', strtotime('+120 minutes', $idate1));
$_POST['due_date'] = $time1;
我已经尝试过这个功能,它很好用,除非我使用像(2013-11-26 12:30)这样的日期,他给了我(2013-11-27 04:30:00)问题出在 12:30
function addRollover($givenDate, $addtime) {
$starttime = 8.5*60; //Start time in minutes (decimal hours * 60)
$endtime = 18.5*60; //End time in minutes (decimal hours * 60)
$givenDate = strtotime($givenDate);
//Get just the day portion of the given time
$givenDay = strtotime('today', $givenDate);
//Calculate what the end of today's period is
$maxToday = strtotime("+$endtime minutes", $givenDay);
//Calculate the start of the next period
$nextPeriod = strtotime("tomorrow", $givenDay); //Set it to the next day
$nextPeriod = strtotime("+$starttime minutes", $nextPeriod); //And add the starting time
//If it's the weekend, bump it to Monday
if(date("D", $nextPeriod) == "Sat") {
$nextPeriod = strtotime("+2 days", $nextPeriod);
}
//Add the time period to the new day
$newDate = strtotime("+$addtime", $givenDate);
//print "$givenDate -> $newDate\n";
//print "$maxToday\n";
//Get the new hour as a decimal (adding minutes/60)
$hourfrac = date('H',$newDate) + date('i',$newDate)/60;
//print "$hourfrac\n";
//Check if we're outside the range needed
if($hourfrac < $starttime || $hourfrac > $endtime) {
//We're outside the range, find the remainder and add it on
$remainder = $newDate - $maxToday;
//print "$remainder\n";
$newDate = $nextPeriod + $remainder;
}
return $newDate;
}