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

前端 未结 1 617
南笙
南笙 2021-01-26 13:14

How would I structure the conditions to add two hours only to dates between 08:30 in the morning until 18:30 of the evening, excluding Saturday and Sunday?

In the case t

相关标签:
1条回答
  • 2021-01-26 13:35

    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

    0 讨论(0)
提交回复
热议问题