且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

2个日期之间的时差,忽略周末时间

更新时间:2023-01-31 14:15:01

假设您有两个时间戳: $ timestamp1 $ timestamp2 ,则可以减去它们并减去周末数: $ difference-($ weekends * 2 * 24 * 3600).

Assuming that you have two timestamps: $timestamp1 and $timestamp2, you could just subtract them and subtract the number of weekends: $difference - ($weekends*2*24*3600).

function difWeekends($timestamp1, $timestamp2){
    $difference = $timestamp2 - $timestamp1;
    $nextWeekend = strtotime('next Saturday', $timestamp1);
    $weekends = 0;
    $weekendFound = true;
    while($weekendFound){
        if($nextWeekend < $timestamp2){
            $weekendFound = false;
        } else {
            $nextWeekend = strtotime('+7 days', $nextWeekend);
            $weekends++;
        }
    }
    $difference -= $weekends*48*60*60;

    $hours = $difference % 3600; // Not sure about this, I assume you already got this...
    $difference -= $hours*3600;
    $minutes = $difference % 60;
    return array('hours'=>$hours, 'minutes'=>$minutes);        
}

需要

function difWeekends($timestamp1, $timestamp2){
    $difference = $timestamp2 - $timestamp1;

    // Calculate the start of the first next weekend
    $nextWeekendStart = strtotime('next Friday 17:30', $timestamp1);

    // Calculate the end of the first next weekend
    $nextWeekendEnd = strtotime('next Monday 9:00', $nextWeekendStart);

    // This wil hold the number of weekend-seconds that needs to be subtracted
    $weekendSubtract = 0;

    $weekendFound = true;
    while($weekendFound){
        // If $timestamp2 ends before the next weekend, no weekend is found. [] = weekends, --- is time range
        // ---  [    ]
        if($timestamp2 < $nextWeekendStart){
            $weekendFound = false;
        } else {
            // ----[--  ]
            if($timestamp2 < $nextWeekendEnd){
                $weekendSubtract += $timestamp2-$nextWeekendStart;
                $weekendFound = false; // Last weekend was found
            } else {
                // ---[----]---
                $weekendSubtract += $nextWeekendEnd - $nextWeekendStart;
                $nextWeekendStart += 7*24*60*60;
                $nextWeekendEnd += 7*24*60*60;
            }
        }
    }
    $difference -= $weekendSubtract;

    $hours = $difference % 3600; // Not sure about this, I assume you already got this...
    $difference -= $hours*3600;
    $minutes = $difference % 60;
    return array('hours'=>$hours, 'minutes'=>$minutes);        
}