PHP Laravel 如何根据请假记录的起止日期获取Y-m-d格式的日期数组
目标需求
从Leave表中提取每条请假记录覆盖的全量日期,将每条记录的start_date到end_date区间内的所有日期整理为Y-m-d格式的字符串,用于和同样采用Y-m-d格式的getDays方法做结果比对。
现有实现代码
当前控制器类中编写的getLeaves方法代码如下:
private function getLeaves() { $leavesList = Leave::where('clinic_id', '=', $_SESSION['clinic_ID'])->get(); $leavesArray = json_decode($leavesList, true); foreach($leavesArray as $leave){ //Convert each data from table to Y-m-d format to compare $leaves[] = CarbonPeriod::create(date('Y-m-d', strtotime($leave['start_date'])), date('Y-m-d', strtotime($leave['end_date']))); } return $leaves; }
现存问题
当前方法输出的结果不符合格式要求:
[["2021-05-20T16:00:00.000000Z"],["2021-05-06T16:00:00.000000Z","2021-05-07T16:00:00.000000Z"]]
返回内容是带时区标识的ISO标准时间格式,并非目标的纯日期Y-m-d格式。出现该问题的核心原因是代码直接将CarbonPeriod对象本身存入返回数组,没有对周期内包含的每个日期实例做格式化转换。
修正方案
- 移除冗余的
json_decode步骤:Leave::get()返回的是模型集合,可直接通过模型属性访问字段值,不需要先转JSON再解码为数组,减少无意义的类型转换消耗。 - 新增对
CarbonPeriod周期的遍历逻辑:逐个取出周期内的日期实例,调用format('Y-m-d')方法转换为要求格式的字符串,再存入返回数组。 - 提前定义
$leaves初始为空数组,避免PHP抛出未定义变量的警告。
修正后的代码如下:
private function getLeaves() { $leaves = []; $leavesList = Leave::where('clinic_id', $_SESSION['clinic_ID'])->get(); foreach($leavesList as $leave){ // 生成覆盖请假全周期的日期范围 $dateRange = CarbonPeriod::create( date('Y-m-d', strtotime($leave['start_date'])), date('Y-m-d', strtotime($leave['end_date'])) ); $currentLeaveDates = []; // 遍历周期内每个日期,转为Y-m-d格式 foreach ($dateRange as $dateItem) { $currentLeaveDates[] = $dateItem->format('Y-m-d'); } $leaves[] = $currentLeaveDates; } return $leaves;
修正后输出的结果为纯Y-m-d格式的日期二维数组,示例结构:[["2021-05-20"], ["2021-05-06", "2021-05-07"]]
可直接和getDays方法的返回值做比对。
内容的提问来源于stack exchange,提问作者junmingyeo98
相关产品推荐
相关产品推荐

