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

时间:2014-11-27 15:33:58

标签: 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...");
    }

1 个答案:

答案 0 :(得分: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...");
}

对于早于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...");
}
相关问题