PHP生成近七(N)天日期的几个方法

目录

近七天(支持过去七天和未来七天,具体天数可根据需求调整) 

计算近N天所有日期并返回其数组

计算两日期之间所有日期并返回其数组

计算两日期之间相差的天数


近七天(支持过去七天和未来七天,具体天数可根据需求调整) 

if(!function_exists('getSevenDate')){
    /**
     * 获取最近七天所有日期
     * @param string $time 时间戳
     * @param string $format 格式化
     * @param string $operation 运算符 +表示某日期过去七天,-表示某日期未来七天
     * @return array 日期数组
     */
    function getSevenDate($time = '', $format='Y-m-d', $operation='+'){
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i=1; $i<=7; $i++){
            $date[$i] = date($format ,strtotime( "{$operation}" . $i-7 .' days', $time));
        }
        return $date;
    }
}

计算近N天所有日期并返回其数组

if (!function_exists('getEveryDayByRecentDate')) {
    /**
     * 生成近N天具体日期
     * @param int $dayNum 生成最近天数
     * @param string $fmt 生成的日期格式
     * @return array 返回具体的日期数组
     */
    function getEveryDayByRecentDate($dayNum, $fmt = 'Y-m-d') {
        $days = [];
        for ($i = 0; $i < $dayNum; $i++) {
            $days[] = date($fmt, strtotime(' -'. $i . 'day'));
        }
        return $days;
    }
}

计算两日期之间所有日期并返回其数组

if (!function_exists('dayAryByTwoDate')) {
    /**
     * 计算两个日期之间所有每天的日期并作为数组返回
     * @param int $days 生成日期数量
     * @param string $startDate 开始日期日期(不传则以当前时间计算,日期时间格式)
     * @return array $datAry 日期数组
     * @throws Exception
     */
    function dayAryByTwoDate(int $days, $startDate = 'now')
    {
        $datetime = new \DateTime($startDate);
        $interval = \DateInterval::createFromDateString('+1 day');
        $period = new \DatePeriod($datetime, $interval, $days);
        $datAry = [];
        foreach ($period as $date) {
            $datAry[] = $date->format('Y-m-d');
        }
        return $datAry;
    }
}

计算两日期之间相差的天数

if(!function_exists('diffBetweenTwoDays'))
{
    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后,求之前可以采用泰勒公式)
     * @param string $day1
     * @param string $day2
     * @return number
     */
    function diffBetweenTwoDays(string $day1, string $day2)
    {
        //$second1 = strtotime(date('Y-m-d', strtotime($day1)));
        //$second2 = strtotime(date('Y-m-d', strtotime($day2)));
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return floor(($second1 - $second2) / 86400);
    }
}

 

***************************只要思想不滑坡,办法总比困难多***************************

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值