发新帖

[PHP] 计算两个日期之间的天数差

零下一度 12天前 104
/**
 * 计算两个日期之间的天数差
 * @param string $date1 第一个日期
 * @param string $date2 第二个日期
 * @param string $format 日期格式,默认 'Y-m-d'
 * @return int 天数差
 */
function getDaysBetweenDates($startdate, $enddate, $format = 'Y-m-d') {
    try {
        $dateTime1 = DateTime::createFromFormat($format, $startdate);
        $dateTime2 = DateTime::createFromFormat($format, $enddate);
        
        if (!$dateTime1 || !$dateTime2) {
            throw new Exception("日期格式不正确");
        }
        
        // 确保时间部分为 00:00:00
        $dateTime1->setTime(0, 0, 0);
        $dateTime2->setTime(0, 0, 0);
        
        $interval = $dateTime1->diff($dateTime2);
        return (int)$interval->format('%a');
    } catch (Exception $e) {
        return "错误: " . $e->getMessage();
    }
}


function getDaysBetweenDates($startDate, $endDate) {
	    try {
	        $start = new DateTime($startDate);
		    $end = new DateTime($endDate);
		    $interval = $start->diff($end);
		    // 获取带符号的天数
		    $days = $interval->days;
		    // 如果结束日期早于开始日期,返回负数
		    if ($start > $end) {
		        return -$days;
		    } 
		    return $days;
		    
	    } catch (\Exception $e) {
	        return "错误: " . $e->getMessage();
	    }
}
最新回复 (0)
返回
零下一度
主题数
964
帖子数
0
注册排名
1