比较日期,每月期限+ 1天

fra*_*n35 -1 php date date-math

我需要将当前日期与开始日期进行比较,想法是每个月+ 1天它将返回,好像只有一个月过去了.因此,如果开始日期是2014-10-27,那么在2014-11-27它仍将显示不到一个月前,并且在2014-11-28它将显示一个多月前.

目前我有:

     $start_datetime = '2014-10-27';
    // true if my_date is more than a month ago

    if (strtotime($start_datetime) < strtotime('1 month ago')){
    echo ("More than a month ago...");
    } else {
    echo ("Less than a month ago...");
    }
Run Code Online (Sandbox Code Playgroud)

Joh*_*nde 5

DateTime最适合PHP中的日期数学.DateTime对象具有可比性,这使得它也非常易读.

$start_datetime = new DateTimeImmutable('2014-10-27');
$one_month_ago  = $start_datetime->modify('- 1 month');

if ($start_datetime < $one_month_ago){
    echo ("More than a month ago...");
} else {
    echo ("Less than a month ago...");
}
Run Code Online (Sandbox Code Playgroud)

对于早于5.5的PHP版本,您需要克隆$startDate以使其工作:

$start_datetime = new DateTime('2014-10-27');
$one_month_ago  = clone $start_datetime;
$one_month_ago  = $one_month_ago->modify('- 1 month');

if ($start_datetime < $one_month_ago){
    echo ("More than a month ago...");
} else {
    echo ("Less than a month ago...");
}
Run Code Online (Sandbox Code Playgroud)