2016-11-24 197 views
0

我有一個月的工作日計算代碼。 如果在一個月有1個期間,一切都算好。在一個月中計算日期

但是,如果在月(這種情況下,八月)是一個週期以上不工作

Dates example <br> 
2016-08-02 - 2016-08-04 (3 working days)<br> 
then <br> 
2016-08-08 - 2016-08-10 (3 working days)<br> 
and 2016-08-24 - 2016-09-02 (6 working days)<br> 

因此,這將是12個工作日內在八月

這裏是我的mysqli查詢:

$getaways = mysqli_query($conn, "SELECT * FROM employeesAbsence 
            WHERE workerID='".$row['worker']."' 
            AND fromDate LIKE '%2016-08%' 
            AND toDate LIKE '%2016-08%'); 
$aways_row = mysqli_fetch_array($getaways); 
$fDate = $aways_row['fromDate']; 
$tDate = $aways_row['toDate']; 

這裏是php:

function get_days($start, $end) 
{ 
    $begin = new DateTime($start); 
    $end = new DateTime($end); 
    //$end = $end->modify('+1 day'); //add one day so as to include the end date of our range 

    $total_days = 0; 
    //this will calculate total days from monday to friday in above date range 
    for($i = $begin; $i <= $end; $i->modify('+1 day')) 
    { 
     // Check that the date is between Monday and Friday and only in August 
     if(($i->format('N') >= 1 && $i->format('N') <= 5) && $i->format('m') == '08') 
     { 
      $total_days++; 
     } 
    } 
    return $total_days; 
} 

$total = 0; 
$total += get_days($fDate, $tDate); 

此代碼返回3爲工作日

我缺少什麼或者做錯了多少? 謝謝。

+0

那麼作爲您的測試之一是'$ i-> format('m')=='08''八月份的日期不會被計入 – RiggsFolly

+0

我假定在查詢結尾缺少'''只是一個TYPO? – RiggsFolly

+0

@RiggsFolly即時與八月工作現在將改變,以後!也是隻是一個錯字! –

回答

1

好吧我想我現在得到了這個問題,你從查詢中得到了多於一行的數據,但你只在你的計算中使用第一行。

您需要遍歷查詢返回的3行。

function get_days($start, $end) 
{ 
    $begin = new DateTime($start); 
    $end = new DateTime($end); 

    $total_days = 0; 
    //this will calculate total days from monday to friday in above date range 
    for($i = $begin; $i <= $end; $i->modify('+1 day')) { 
     // Check that the date is between Monday and Friday and only in August 
     if(($i->format('N') >= 1 && $i->format('N') <= 5) && $i->format('m') == '08') { 
      $total_days++; 
     } 
    } 
    return $total_days; 
} 

$getaways = mysqli_query($conn, "SELECT * FROM employeesAbsence 
            WHERE workerID='".$row['worker']."' 
            AND MONTH(fromDate) = 8 
            AND MONTH(toDate) = 8"); 

if (! $getaways) { 
    echo mysqli_error($getaways); 
    exit; 
} 

// just check how many row you get back 
echo 'Query generated ' . mysqli_num_rows($getaways) . ' rows'; 

$total = 0; 
while ($row = mysqli_fetch_array($getaways)){ 
    $total += get_days($row['fromDate'], $row['toDate']); 
} 
echo $total; 

爲了得到你所suggestiong你想要的結果,請嘗試更改查詢

$getaways = mysqli_query($conn, "SELECT * FROM employeesAbsence 
            WHERE workerID='".$row['worker']."' 
            AND MONTH(fromDate) = 8"); 

那麼這將返回您在節日在八月開始,無論在假期結束的所有行。

+0

有趣的仍然是 –

+0

我添加了您的查詢返回的行數的打印。也許這會在查詢中發現問題! – RiggsFolly

+0

哪裏有記錄1哪裏沒有記錄那裏0返回 –