【发布时间】:2013-11-26 22:14:13
【问题描述】:
我将如何构造条件以仅在早上 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;
}
【问题讨论】:
标签: php date datetime date-math