计算两个日期相隔多少年,多少月,多少天

核心方法
	/**
     * @name: 计算两个日期相隔多少年,多少月,多少天
     * @param {date} $date1 [格式如:2011-11-5]
     * @param {date} $date2 [格式如:2012-12-01]
     * @author: Turbo
     * @Date: 2023-01-05 13:35:37
     */    
    public function diffDate($date1, $date2)
    {
    
    
        if (strtotime($date1) > strtotime($date2)) {
    
    
            $tmp = $date2;
            $date2 = $date1;
            $date1 = $tmp;
        }
        list($Y1, $m1, $d1) = explode('-', $date1);
        list($Y2, $m2, $d2) = explode('-', $date2);
        $Y = $Y2 - $Y1;
        $m = $m2 - $m1;
        $d = $d2 - $d1;
        if ($d < 0) {
    
    
            $d += (int)date('t', strtotime("-1 month $date2"));
            $m--;
        }
        if ($m < 0) {
    
    
            $m += 12;
            $Y--;
        }
        // 如果天数大于等于结束日月份天数
        $end_month_start_day = date('Ym01', strtotime($date2));
        $end_month_end_day = date('Ymd', strtotime("{
      
      $end_month_start_day} + 1 month -1 day"));
        $end_month_day = range($end_month_start_day, $end_month_end_day, 1);
        if ($d >= count($end_month_day)) {
    
    
            $m = $m + 1;
            $d = $d - count($end_month_day);
        }

        return array('year' => $Y, 'month' => $m, 'day' => $d);
    }
调用
$res = $this->diffDate('2022-01-05', '2023-01-05');
dump($res);die;

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_15957557/article/details/128562012