【发布时间】:2022-01-24 12:19:24
【问题描述】:
我想计算特定周内的空闲天数(缺勤)。我使用返回以下数据的 API:
{
"count": 1,
"data": [
{
"id": "11ec62ff1df2654d8bd6f1d234a6c496",
"type": "HOLIDAY",
"from": "2021-12-22",
"to": "2021-12-23",
"resourceId": "11ec46d6547a00728be3e1ed8ff29535",
"createdAt": "2021-12-22T08:14:00"
}
],
"success": true
}
这些是假期和疾病数据。我有一份每周报告,我需要计算那一周的缺勤天数。我需要找到一种简单的方法来计算一周中的缺勤天数。
我尝试过使用https://www.php.net/manual/de/datetime.format.php 并将其转换为“z”格式,但它看起来并不优雅,从性能角度来看,我认为它不是最好的。
//The week range
$weekStart = new DateTime("2021-12-20");
$weekEnd = new DateTime("2021-12-24");
//The Planned absence
$absenceStart = new DateTime("2021-12-22");
$absenceEnd = new DateTime("2021-12-23");
//Specify the DateInterval for calculating the period
$interval = DateInterval::createFromDateString('1 day');
//Need to add the interval to the end date in order to consider the end as well
$weekEnd->add($interval);
$absenceEnd->add($interval);
//Getting the 2 periods week and absence
$weekPeriod = new DatePeriod($weekStart, $interval, $weekEnd);
$absencePeriod = new DatePeriod($absenceStart, $interval, $absenceEnd);
$weekArray = array();
$absenceArray = array();
//put the day number format('z') into an array of the week
foreach ($weekPeriod as $i => $dt) {
$weekArray[$i] = $dt->format('z');
}
//put the day number format('z') into an array of the absence
foreach ($absencePeriod as $i => $dt) {
$absenceArray[$i] = $dt->format('z');
}
//get the intersection between both arrays
$ergebnis = array_intersect($weekArray, $absenceArray);
//calculate the number of entries
echo "The employee has <b>".count($ergebnis)."</b> free days in the week from 2021-12-20 until 2021-12-24";
这是返回正确的信息。
The employee has 2 free days in the week from 2021-12-20 until 2021-12-24
任何人都可以建议是否有更好的方法,或者我是否可以至少对其进行调整以使其更优雅和性能更好?
非常感谢
【问题讨论】: