-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...");
    }
John Conde
  • 217,595
  • 99
  • 455
  • 496
fran35
  • 145
  • 12

1 Answers1

5

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...");
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • @vascowhite I've been anticipating it, too. Fortunately making this work with PHP versions older than 5.5 just requires one more line of code. – John Conde Nov 27 '14 at 15:45
  • Also see the date echo'd in the link :) I do like immutable objects though. – vascowhite Nov 27 '14 at 15:46
  • And I am in older version, can you please ellaborate @JohnConde – fran35 Nov 27 '14 at 16:09
  • Thanks, unfortunately it still doesn't works, I got: stack trace: #0 E:\www\root\compare\comp2.php(5): DateTime->__construct('2014-10-27') #1 {main} thrown in E:\www\root\compare\comp2.php on line 5. line 5 = $start_datetime = new DateTime('2014-10-27'); – fran35 Nov 27 '14 at 16:45
  • @JohnConde I believe you ;) – Funk Forty Niner Nov 27 '14 at 18:10