美文网首页
php 实现补齐缺少日期时间2023-07-18

php 实现补齐缺少日期时间2023-07-18

作者: 阿然学编程 | 来源:发表于2023-07-17 13:56 被阅读0次
    • 本次需要实现的功能是为了配合前端实现柱状图以及条形图,而去处理出柱状图所需要的补齐区间日期中缺少的数据。
    /**
     * 补齐时间日期
     * 使用案例:统计报表,折线图,柱状图
     * @param $startDate 开始时间
     * @param $endDate 结束时间
     * @param array $dates 
     * @param string $interval 天:day,小时:hours,分钟:minutes,秒:seconds
     * @param string $format 
     * @return array
     */
    function fill_date($startDate, $endDate, array $dates = array(), $interval = '1 day', $format = 'Y-m-d H:i:s')
    {
        $allDates = array();
        $currentDate = strtotime($startDate);
        $endDate = strtotime($endDate);
    
        while ($currentDate <= $endDate) {
            $dateString = date($format, $currentDate);
            $allDates[] = $dateString;
            $currentDate = strtotime('+' . $interval, $currentDate);
        }
    
        if ($dates) {
            $allDates = array_diff($allDates, $dates);
        }
    
        return array_values($allDates);
    }
    
    • 使用示例
    • 补齐日期时间
            $dates = [
                "2022-12-19",
                "2022-12-20",
                "2022-12-23"
            ];
    
            $start_time = "2022-12-10";
            $end_time = "2022-12-31";
    
            $a = fill_date($start_time, $end_time, $dates);
    
            dump($a);
    
    image.png
    • 补齐 N小时时间
            $start_time = "2022-12-10";
            $end_time = "2022-12-31";
            //补齐间隔5小时的日期时间
            $a = fill_date($start_time, $end_time,[],'5 hours');
            dump($a);
    
    image.png
    • 补齐 N分钟时间
            $start_time = "2022-12-10";
            $end_time = "2022-12-31";
    
            $a = fill_date($start_time, $end_time,[],'5 minutes');
    
            dump($a);
    
    image.png

    相关文章

      网友评论

          本文标题:php 实现补齐缺少日期时间2023-07-18

          本文链接:https://www.haomeiwen.com/subject/gvdgudtx.html