Compare dates, monthly period + 1 day

132 Views Asked by At

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

There are 1 best solutions below

5
On

DateTime is best suited for date math in PHP. DateTime objects are comparable which makes this very readable, too.

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

For PHP versions older than 5.5 you need to clone $startDate for this to work:

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