2

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?

4
  • 1
    I suggest strtotime(). Commented Sep 15, 2011 at 1:44
  • 1
    Hmmm, but isn't '2011-09-13' < '2011-09-15' true? Commented Sep 15, 2011 at 1:47
  • in PHP are string comparable lexigraphically using <? Probably best to convert to some numeric type (unix timestamp?) and compare that instead. Commented Sep 15, 2011 at 1:47
  • 1
    @Evan Teran: they are. And the code should work Commented Sep 15, 2011 at 1:50

4 Answers 4

4

To compare dates you have to use strtotime() for $row['start_date'] and time()

if(strtotime($row['start_date']) < time())
Sign up to request clarification or add additional context in comments.

1 Comment

You don't "have to" use strtotime()
2

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';

}

Comments

1

Use strtotime() to convert the string to unix timestamp then compare. Or use the DateTime object.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.