2017-07-10 78 views
-1

我試圖得到兩個日期之間的工作日和週末計數,但對於週末我得到0值。得到工作日和週末的計數從給出兩個日期在PHP

下面是代碼:

<?php 

function daysCount($startDate, $endDate) 
{ 
    $weekdayCount = $weekendCount =0; 
    $startTimestamp = strtotime($startDate); 
    $endTimestamp = strtotime($endDate); 

    for ($i = $startTimestamp; $i <= $endTimestamp; $i = $i + (60 * 60 * 24)) 
    { 
     if (date("N", $i) <= 5) 
     { 

      $weekdayCount = $weekdayCount + 1; 

     } 
     if (date("N", $i) == 6 && $i%7 == 0) 
     { 
      $weekendCount = $weekendCount + 1; 
     } 
    } 
    return array('weekdayCount' => $weekdayCount, 'weekendCount' => $weekendCount); 
} 

$startDate = "2017-07-03"; 
$endDate = "2017-07-10"; 
$days = daysCount($startDate, $endDate); 
print_r($days); 

?> 

這是演示鏈接demo updated

有人可以幫助我獲得weekendCount?

+0

那不是相同的代碼您的演示,該代碼我們糾正? – Flosculus

+0

也是週末,這是否意味着作爲一個組?例如星期六和星期日將算作1個週末?或者說,週六和週日都是單獨的週末? – ThisGuyHasTwoThumbs

+0

@Flosculus:我給出的代碼正在糾正 – 06011991

回答

1

也許這樣一來,基地演示鏈接:

function number_of_working_days($startDate, $endDate) 
{ 
    $workingDays = 0; 
    $startTimestamp = strtotime($startDate); 
    $endTimestamp = strtotime($endDate); 
    for ($i = $startTimestamp; $i <= $endTimestamp; $i = $i + (60 * 60 * 24)) { 
     if (date("N", $i) <= 5) $workingDays = $workingDays + 1; 
    } 
    return $workingDays; 
} 

function number_of_weekend_days($startDate, $endDate) 
{ 
    $weekendDays = 0; 
    $startTimestamp = strtotime($startDate); 
    $endTimestamp = strtotime($endDate); 
    for ($i = $startTimestamp; $i <= $endTimestamp; $i = $i + (60 * 60 * 24)) { 
     if (date("N", $i) > 5) $weekendDays = $weekendDays + 1; 
    } 
    return $weekendDays; 
} 

$startDate = "2016-11-01"; 
$endDate = "2016-11-30"; 
$workingDays = number_of_working_days($startDate, $endDate); 
$weekendDays = number_of_weekend_days($startDate, $endDate); 
echo "Total number of working days between $startDate and $endDate is: " . $workingDays . " day(s)."; 
echo "Total number of weekend days between $startDate and $endDate is: " . $weekendDays . " day(s)."; 
+0

謝謝你工作:) – 06011991

相關問題