-1

I need to compare current date against a starting date, idea being that on every month + 1 day it will return as if only one month has gone by. So if starting date is 2014-10-27, on 2014-11-27 it will still show Less than a month ago, and on 2014-11-28 it'll show more than a month ago.

Currently I have:

     $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...");
}

$startDate5.5 より古いバージョンの PHP の場合、これを機能させるにはクローンを作成する必要があります。

$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 に答える