johnny_s johnny_s - 2 months ago 14
PHP Question

PHP date comparison and strtotime

Using WIndows, XAMPP 5.6.8 I am building a simple web app in HTML and PHP.

I would like to compare a date retrieved from a database with today's date.

I have a function that successfully returns a string value (in the UK date format

d-m-y
).

My code so far is;

$expDate = get_api_data($id); // returns a string
var_dump($expDate); // this prints string(8) "31-12-19"


Using this
$expDate
value I would like to achieve something like;

if (strtotime('d-m-y', $expDate) > time()) { // if date > than today
echo 'date is greater than today';
}
elseif (strtotime('d-m-y', $expDate) < time()) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}


Currently I am receiving date is less than today - even though the date is
31-12-19
. I'm not sure if I am approaching this the correct way?

Any help would be greatly appreciated as I have alreday spent a lot of time researching answers to no avail.

Answer

I got this error when executing your code

PHP Notice: A non well formed numeric value encountered

You should look at the doc in order to make a good usage of this function: http://php.net/manual/fr/function.strtotime.php

The first param should be a time, not a format.

By the way, i prefer use DateTime class to compare dates, you can do:

<?php

  $expectedDate = \DateTime::createFromFormat('d-m-y', get_api_data($id));
  $nowDate = new \DateTime();

  if ($expectedDate > $nowDate) { // if date > than today
    echo 'date is greater than today';
  }
  elseif ($expectedDate < $nowDate) { // if date < than today
    echo 'date is less than today';
  }
  else {
    echo 'date not found';
  }