将工作时间添加到时间戳
答
试试这个坏男孩。
您可以指定是否将周末包括为工作日等。不考虑假期。
<?php
function addWorkingHours($timestamp, $hoursToAdd, $skipWeekends = false)
{
// Set constants
$dayStart = 8;
$dayEnd = 16;
// For every hour to add
for($i = 0; $i < $hoursToAdd; $i++)
{
// Add the hour
$timestamp += 3600;
// If the time is between 1800 and 0800
if ((date('G', $timestamp) >= $dayEnd && date('i', $timestamp) >= 0 && date('s', $timestamp) > 0) || (date('G', $timestamp) < $dayStart))
{
// If on an evening
if (date('G', $timestamp) >= $dayEnd)
{
// Skip to following morning at 08XX
$timestamp += 3600 * ((24 - date('G', $timestamp)) + $dayStart);
}
// If on a morning
else
{
// Skip forward to 08XX
$timestamp += 3600 * ($dayStart - date('G', $timestamp));
}
}
// If the time is on a weekend
if ($skipWeekends && (date('N', $timestamp) == 6 || date('N', $timestamp) == 7))
{
// Skip to Monday
$timestamp += 3600 * (24 * (8 - date('N', $timestamp)));
}
}
// Return
return $timestamp;
}
// Usage
$timestamp = time();
$timestamp = addWorkingHours($timestamp, 6);
+0
达姆好孩子;)这真的是工作的人,谢谢! – spamec 2010-01-28 10:33:52
答
一个更紧凑的版本:
function addWhours($timestamp, $hours, $skipwe=false, $startDay='8', $endDay='18')
{
$notWorkingInterval = 3600 * (24 - ($endDay - $startDay));
$timestamp += 3600*$hours;
$our = date('H', $timestamp);
while ($our < $startDay && $our >= $endDay) {
$timestamp += $notWorkingInterval;
$our = date('H', $timestamp);
}
$day = date('N', $timestamp);
if ($skipwe && $day >5) {
$timestamp += (8-$day)*3600*24;
}
return $timestamp;
}
我认为我们需要一些详细信息。根据您的示例,您是否只处理离散小时,或者它是否实际上使用时间戳,正如您的问题所暗示的那样?我也怀疑在这个算法的任何实际应用中,你都需要考虑边界条件,例如下午6点实际上是一个有效的回应? – 2010-01-28 09:53:11
你是对的...我有开始日期作为时间戳。然后,我不得不增加几个小时(像3等)。你关于边界的问题是正确的(关于这种情况并没有),而下午6点是无效的,所以结果应该是早上8点(具体的日期时间不只是一小时)。 – spamec 2010-01-28 10:04:03