3

I'm trying to compare the current date with a date field returned by a MySQL query called "expiry_date". This field is a date field formatted as YYYY-MM-DD I'm using If Else, to initialize a variable with the result as follows:

$today = $expiry_date = date("d-M-Y", strtotime("now"));
if ($row['expiry_date'] > $today)
{
    $msg="Not Expired";
}
else
{
    $msg="Expired";
}

This doesn't appear to work and I would appreciate any suggestions on how to fix this.

7
  • You're comparing d-M-Y to Y-m-d, per your own statement... also date defaults to the current time, so you're creating a string, converting it to a timestamp, then sending it to a function that defaults to that exact same timestamp. Commented Jun 14, 2013 at 15:37
  • 2
    "Does not appear to work" => it would help if you said exactly how. Commented Jun 14, 2013 at 15:38
  • compare strtotime($str1) and strtotime($str2) this should do it Commented Jun 14, 2013 at 15:40
  • since $row sounds like something of a database: If you can filter it on the database side, filter it on the database side (in the query). Correctly used, mysql beats any php application for matters of sorting, joining, filtering. Commented Jun 14, 2013 at 15:43
  • Thanks for spotting this. Ive corrected but still doesnt work. Commented Jun 14, 2013 at 16:04

3 Answers 3

2
$today = $expiry_date = new \Datetime();
$row_expiry_date = date_create_from_format('Y-m-d', $row['expiry_date']);
if ($row_expiry_date > $today)
{
     $msg="Not Expired";
} else {
     $msg="Expired";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi ARMBouhali, now that I;ve implemented your suggestion correctly, it works. Many thanks for this.
@Taffman, Don't forget to accept the answer, if that's what you need.
0

You have two options, you can either format the dates the same and compare as strings

$today = $expiry_date = date("Y-m-d", strtotime("now"));
if ($row['expiry_date'] < $today)

or you can convert the row data to a unix timestamp for the comparison.

$today = $expiry_date = time();
if (strtotime($row['expiry_date']) < $today)

Comments

0

you have $today = $expiry_date = which should be $today = or $expiry_date =

$today = date("Y-m-d");

if (strtotime($row['expiry_date']) > $strtotime($today))
{
     echo "not expired";
} else {
    echo "expired";
}

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.