-1

我需要将当前日期与开始日期进行比较,想法是每个月 + 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...");
    }
4

1 回答 1

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...");
}
于 2014-11-27T15:35:58.317 回答