2010-06-02 93 views
10

如何計算php中兩個日期之間星期六和星期日的數量?計算星期六和星期日的數量

是否有用於此目的的任何內置功能?

+0

的[計算工作日]可能重複上來(http://stackoverflow.com/questions/336127/calculate-business-days) – 2014-01-14 10:45:30

回答

5

有一個相關的問題已經在這裏,Calculate business days

你可以用它來減從7到週末的日子,或類似的。

4

我不認爲有一個內置的爲,但這應該做的工作:

$startTime = START_TIMESTAMP; 
$endTime = END_TIMESTAMP; 
$time = $startTime; 
$count = 0; 

while(date('w', $time) != 0) { // 0 (for Sunday) through 6 (for Saturday) 
    $time += 86400; 
} 

while($time < $endTime) { 
    $count++; 
    $time += 7 * 86400; 
} 
+0

如果startdate中的時間戳記星期六到來,該怎麼辦星期六 – nik 2010-06-02 14:42:56

+0

它也可以工作,'date('w',$ time)== 0',所以你去第二個時候,'$ count ++' ,你至少有一個星期六。 – 2010-06-02 14:58:36

+1

而不是'while(date('w',$ time)!= 0)''你可以做'$ time = strtotime(「Saturday」)'或'$ time = strtotime(「Sunday」)''。 – 2010-06-02 15:16:47

0
<?php 
date_default_timezone_set("Europe/Lisbon"); 
$d1 = new DateTime("2009-06-01"); /* inclusive */ 
$d2 = new DateTime("2009-07-01"); /* exclusive */ 

$interval = $d2->diff($d1); 
$number_of_days = $interval->format("%d"); 

$number_of_weekends = $number_of_days/7; 
$remainder = $number_of_days % 7; 

if ($remainder >=2 && $d1->format("D") == "Sat") 
    $number_of_weekends++; 
elseif ($d1->format("w") + $remainder >= 8) 
    $number_of_weekends++; 

我可能錯過了最後一個條件之一,一定要檢查它與不同的開始日期。 (如果您發現錯誤,請隨時編輯此答案)。

0

有絕對沒有內置的函數,該函數,但你可以使用的strtotime循環天

$start = strtotime('2010-01-01'); 
$end = strtotime('2010-01-09'); 

function numWeekdays($start_ts, $end_ts, $day, $include_start_end = false) { 

    $day = strtolower($day); 
    $current_ts = $start_ts; 
    // loop next $day until timestamp past $end_ts 
    while($current_ts < $end_ts) { 

     if(($current_ts = strtotime('next '.$day, $current_ts)) < $end_ts) { 
      $days++; 
     } 
    } 

    // include start/end days 
    if ($include_start_end) { 
     if (strtolower(date('l', $start_ts)) == $day) { 
      $days++; 
     } 
     if (strtolower(date('l', $end_ts)) == $day) { 
      $days++; 
     } 
    } 

    return (int)$days; 

} 

echo numWeekDays($start, $end, 'saturday', false); 
1

讓我們KISS(保持簡單愚蠢)。爲什麼這麼複雜?

function countWeekendDays($start, $end) 
{ 
    // $start in timestamp 
     // $end in timestamp 


    $iter = 24*60*60; // whole day in seconds 
    $count = 0; // keep a count of Sats & Suns 

    for($i = $start; $i <= $end; $i=$i+$iter) 
    { 
     if(Date('D',$i) == 'Sat' || Date('D',$i) == 'Sun') 
     { 
      $count++; 
     } 
    } 
    return $count; 
    } 
0

我搜索了一段時間了一個簡單的解決方案,工作,決定寫我自己以及與此

 $start = date('Y-m-d'); 
     $end = date('Y-m-d', strtotime($start.' +1 year')); 
     $current = $start; 
     $count = 0; 

     while($current != $end){ 
      if(date('l', strtotime($current)) == 'Saturday'){ 
       $count++; 
      } 

      $current = date('Y-m-d', strtotime($current.' +1 day')); 
     }; 

     echo $count; 
相關問題