Reputation: 11240
I have a simple thing I'm trying to solve.
I have a date stored in a table, and I'm comparing it to a php generated date.
ie:
if($row['start_date'] < date("Y-m-d")) {
// table stored date larger than php date
echo 'hi';
} else {
// php date larger than table stored date
echo 'bye';
}
This seems ok to me, but
if $row['start_date'] === '2011-09-13' AND date("Y-m-d") === '2011-09-15'.
I end up with:
hi
This could be one of those twilight moments where I think left is right and a greater than symbol is actually a less than. So please help me - why doesn't this work?
Upvotes: 2
Views: 105
Reputation: 85458
If $row['start_date'] = '2011-09-13'
and date("Y-m-d") = '2011-09-15'
, then your PHP date is greater than the row's date and thus the if
is true, after all '2011-09-13'
is "smaller (<
)" than '2011-09-15'
. Flip your <
to >
and you'll be fine.
if($row['start_date'] > date("Y-m-d")) {
// table stored date larger than php date
echo 'hi';
} else {
// php date larger than table stored date
echo 'bye';
}
Upvotes: 2
Reputation: 9072
I'm not sure on the validity of comparing dates as strings, using DateTime or strtotime and comparing timestamps may be more robust options but with this date format it should work as strings.
Other than that, your logic seems to work as written (if not as intended). "...13" is less than "...15", so the if
will evaluate to true
and "hi" will be printed.
Judging by the inline comments, it seems it may in fact be one of those twilight moments you speak of.
Upvotes: 0
Reputation: 160833
Use strtotime()
to convert the string to unix timestamp then compare.
Or use the DateTime object.
Upvotes: 1
Reputation: 2784
To compare dates you have to use strtotime()
for $row['start_date']
and time()
if(strtotime($row['start_date']) < time())
Upvotes: 4