user3275707
user3275707

Reputation: 89

Comparing dates in PHP. Why this code returns true?

I'm trying to compare a future date against today's date. This code should return false but it returns true.

return (date('d-m-y') > date('15-03-14')) ? true : false;

Upvotes: 0

Views: 580

Answers (4)

AlexP
AlexP

Reputation: 9857

You can convert the date to an integer using strtotime()

return (strtotime(date('d-m-y')) > strtotime(date('15-03-14'))) ? true : false;

Alternatively use DateTime::diff()

Upvotes: 0

DonCallisto
DonCallisto

Reputation: 29912

First of all, you don't need the shortcircuit if-else statement, just use

return date('d-m-y') > date('15-03-14');

Second you're comparing two strings and not two dates so string comparison isn't the same of date comparison.

You should use strtotime() function or use DateTime object

return (strtotime(date('d-m-y')) > strtotime(date('15-03-14'))

or

return new DateTime() > new DateTime('2014-03-15');

Upvotes: 1

ziollek
ziollek

Reputation: 1993

date function return string, so you compare two strings:

'27-02-14' > '15-03-14'

string is compared char by char, at position 0 we have:

'2' > '1' - and this is true

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Because they are compared as string not date.

If you want to compare as date, use below:

return new DateTime() > new DateTime('2014-03-15');

Upvotes: 0

Related Questions