find if date is older than 30 days

PhpStringDatetimeDateTime

Php Problem Overview


The date string looks like this

2011-08-19 17:14:40

(year-month-day hours:minutes:seconds)

How can I find out if the date is older than the current date with more than 30 days?

Php Solutions


Solution 1 - Php

Try using something like this:

 if(strtotime('2011-08-19 17:14:40') < strtotime('-30 days')) {
     // this is true
 }

Besides, this string looks like it is stored in SQL as datetime/timestamp field. You can directly select all entries from your database with old dates using:

SELECT ... WHERE `datetime` + INTERVAL 30 DAY < NOW()

Solution 2 - Php

If you are on PHP 5.3 or higher you can do:

$someDate = new \DateTime('2011-08-19 17:14:40');
$now = new \DateTime();

if($someDate->diff($now)->days > 30) {
   echo 'The date was more than 30 days ago.';
}

Solution 3 - Php

You can use Carbon as follows

if (30 - ((new \Carbon\Carbon($given_date, 'UTC'))->diffInDays()) < 0) {
    echo "The date is older than 30 days";
}

Solution 4 - Php

strtotime('2011-08-19 17:14:40') + 30 * 24 * 60 * 60 < time();

Solution 5 - Php

With the meringue library, this can be done in at least two ways.

The first one looks like the following:

(new Future(
    new DateTimeParsedFromISO8601String('2011-08-19 17:14:40'),
    new NDays(30)
))
    ->earlierThan(
        new Now()
    );

The semantics is the following: first, you parse a date from an ISO8601 string, then create a future date which is thirty days later than that, and finally compare it with current datetime, that is, now.

The second way is creating an interval from a datetime range and counting the days it consists of. It looks like that:

(new TotalFullDays(
    new FromRange(
        new FromISO8601('2011-08-19 17:14:40'),
        new Now()
    )
))
    ->value();

Both approaches are quite intuitive and don't make you remember special php datetime expressions. Instead, every implementation is autocompleted; you just need to build a correct object that suits your needs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEllaView Question on Stackoverflow
Solution 1 - PhpRiaDView Answer on Stackoverflow
Solution 2 - PhpCollin KrawllView Answer on Stackoverflow
Solution 3 - PhpShriganesh ShintreView Answer on Stackoverflow
Solution 4 - Phpgion_13View Answer on Stackoverflow
Solution 5 - PhpVadim SamokhinView Answer on Stackoverflow