Genadinik
Genadinik

Reputation: 18639

Date comparison in PHP behaving unpredictably

I have a date string like this: 2010-9-30 in my $date_string variable.

When I compare strings like this:

if ( date( 'Y-m-d', strtotime( "+20 days", $date_string ) ) )
{
    // it returns true for all dates
}

The comparison is true for all dates, even from yesterday, which isn't 20 days ago. Any idea why that might be happening?

Thanks!

Upvotes: 1

Views: 62

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270617

You are not making any comparisons between dates. Instead, you are testing whether you can successfully convert the date supplied as the second parameter to strtotime() into a valid date. That result is always true, because every date has a valid date 20 days in the future.

In other words, if date() returns a truthy value your condition is TRUE. It will always return a truthy value unless you pass it an invalid timestamp in its second parameter (for example, the 42nd of February)

If you want to compare the output of that date() call to another date string, you will need an additional operand inside your if():

if ('2011-09-02' == date('Y-m-d', strtotime("+20 days", $date_string))) {

}

Upvotes: 3

Joe
Joe

Reputation: 15802

It's returning the date in the string format of (for example) 2000-01-01, which when converted to boolean is true.

Instead, check for this:

if (time() > strtotime("+20 days", $date_string)) // Returns true if $date_string was in the last 20 days, or is in the future

Obviously, if you want dates more than 20 days old only, just flip the > to a <

Upvotes: 1

Related Questions