查找日期是否小于7天


Find if date is less than 7 days from now

我如何确定到期日期是否小于7天?

有效期格式如下:2016-04-13

我这里有一个代码,但它不起作用:

if($record->$c < date('Y-m-d', strtotime('-7 day'))){
   // this is true
}

希望有人能帮助我。

只需将两个单位转换为unix时间戳,进行减法运算,然后除以86400:

$expiry_date = '2016-04-18';
$today = time();
$interval = strtotime($expiry_date) - $today;
$days = floor($interval / 86400); // 1 day
if($days < 7) {
    echo 'less';
}

或者DateTime类的另一种方式:

$expiry_date = '2016-04-18';
$expiry_date = new DateTime($expiry_date);
$today = new DateTime();
$interval = $today->diff($expiry_date);
$day = $interval->format('%r%a');
if($day < 7) {
    echo 'less';
}

示例条件:

$expiry_date = '2016-04-18';
$today = time();
$interval = strtotime($expiry_date) - $today;
$day = floor($interval / 86400); // 1 day
if($day >= 1 && $day < 7) {
    echo 'between 1 - 7 days';
} elseif($day <= 0) {
    echo 'deadline';
} else {
    echo 'soon';
}

只需根据您要做的事情进行更改/调整即可。

建议探索date_diff()函数:

http://php.net/manual/en/function.date-diff.php

我的挑战不同:

// Count days is date range 
function count_days_in_range($date1, $date2) {
    $date1      = date_create($date1);
    $date2      = date_create($date2);
    $interval   = date_diff($date1, $date2);
    $days       = $interval->days;
    return $days;
}

但这个功能会让你的生活更轻松。