2016-11-24 198 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返回 –