我的代码计算当月缺勤的工作日 如果在月份我需要计算缺勤只有一个人的期间 来自和将来的日期保存在数据库中 示例2016-08-09 - 2016-08-13(假设用户病了)它计算4个工作日
但如果用户有:
2016-07-27 - 2016-08-02(假设用户病了)
2016-08-08 - 2016-08-10(假设用户在职业)和
2016-08-24 - 2016-09-02(再说让用户生病了)
如何统计2016年8月的缺席期间的所有日子?
在这种情况下应该是12天
从数据库获取:
$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'];
计算代码:
$startDate = $fDate;
$endDate = $tDate;
$weekdays = array('1','2','3','4','5'); //monday-friday
$begin = new DateTime($startDate);
$end = new DateTime($endDate);
$end = $end->modify( '+1 day' ); //add one day so as to include the end date of our range
$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $end);
$total_days = 0;
//this will calculate total days from monday to friday in above date range
foreach ($dateRange as $dates) {
if (in_array($dates->format("N"),$weekdays)) {
$total_days++;
}
}
echo $total_days;
答案 0 :(得分:1)
您可能完全在sql查询中执行此操作 - 未经测试但我认为应该没问题。
例如:
select sum( datediff(`toDate`,`fromDate`) ) as 'sickdays'
from `employeesabsence`
where `workerID`=$row['worker']
您可以在where子句中添加其他条件以限制特定日期范围 - 例如:
select sum( datediff(`todate`,`fromdate`) ) as 'sickdays'
from `employeesabsence`
where `workerid`=$row['worker'] and month( `fromdate` ) between 1 and 6;
在sql中找到工作日的解决方案有点棘手,以下内容改编自堆栈中发现的另一个帖子 - 它涉及一个奇特的整数字符串。
例如
select
sum( 5 * ( datediff( `todate`, `fromdate` ) div 7 ) + mid( '0123455401234434012332340122123401101234000123450', 7 * weekday(`fromdate`) + weekday(`todate`) + 1, 1) ) as 'sickdays'
from `employeesabsence` where month(`fromdate`) between 6 and 7
对其进行调整的帖子可以是found here
答案 1 :(得分:1)
PHP DateTime选项:
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( '2016-07-27', '2016-08-02');
$total += get_days( '2016-08-08', '2016-08-10');
$total += get_days( '2016-08-24', '2016-09-02');