dongyoudi1342 2010-01-28 09:38
浏览 60
已采纳

将工作时间添加到时间戳

I need to add working hours to a timestamp. Working hours are from 8am to 6pm. Lets say we have 2pm and I have to add 6 hours. Result should be 10am... any guesses?

Thanks.

  • 写回答

3条回答 默认 最新

  • dqtiober37522 2010-01-28 10:27
    关注

    Try this bad boy.

    You can specify whether to include weekends as working days, etc. Doesn't take into account holidays.

    <?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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误