PHP Add two hours to a date within given hours using function

风流意气都作罢 提交于 2019-12-02 09:49:51

I don't know if you still need this but here it is anyway. Requires PHP 5.3 or higher

<?php
function addRollover($givenDate, $addtime) {
    $datetime = new DateTime($givenDate);
    $datetime->modify($addtime);

    if (in_array($datetime->format('l'), array('Sunday','Saturday')) || 
        17 < $datetime->format('G') || 
        (17 === $datetime->format('G') && 30 < $datetime->format('G'))
    ) {
        $endofday = clone $datetime;
        $endofday->setTime(17,30);
        $interval = $datetime->diff($endofday);

        $datetime->add(new DateInterval('P1D'));
        if (in_array($datetime->format('l'), array('Saturday', 'Sunday'))) {
            $datetime->modify('next Monday');
        }
        $datetime->setTime(8,30);
        $datetime->add($interval);
    }

    return $datetime;
}

$future = addRollover('2014-01-03 15:15:00', '+4 hours');
echo $future->format('Y-m-d H:i:s');

See it in action

Here's an explanation of what's going on:

  1. First we create a DateTime object representing our starting date/time

  2. We then add the specified amount of time to it (see Supported Date and Time Formats)

  3. We check to see if it is a weekend, after 6PM, or in the 5PM hour with more than 30 minutes passed (e.g. after 5:30PM)

  4. If so we clone our datetime object and set it to 5:30PM

  5. We then get the difference between the end time (5:30PM) and the modified time as a DateInterval object

  6. We then progress to the next day

  7. If the next day is a Saturday we progress to the next day

  8. If the next day is a Sunday we progress to the next day

  9. We then set our time to 8:30AM

  10. We then add our difference between the end time (5:30PM) and the modified time to our datetime object

  11. We return the object from the function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!