我的代码可以计算月内的工作日数。 如果在一个月内有一个时期,一切都算好了。
但是如果在月份(这个案例是8月份)不止一个时期它就不起作用
<select class="form-control" name="student_id" id="student" style="width: 100%;"></select>
所以八月份将是12个工作日
这是我的mysqli查询:
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>
这里是php:
$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'];
此代码返回
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);
作为工作天数
我错过了什么或做错了什么? 感谢。
答案 0 :(得分: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;
要获得您想要的结果,请尝试将查询更改为
$getaways = mysqli_query($conn, "SELECT * FROM employeesAbsence
WHERE workerID='".$row['worker']."'
AND MONTH(fromDate) = 8");
这将返回8月假期开始的所有行,无论假期何时结束。