0

I need to compare dates in PHP, in order to check if a contract has expired or not.

For now i'm doing this :

foreach ($this->array as $row)
{
  if(strtotime($date1) > strtotime($row['end_date']))
  {
    $delay = strtotime($row['end_date']);
    $expired = "V";
  }
  else {
    $delay = strtotime($row['end_date']);
    $expired = "X";
  }

So i just know if a contract has expired. I need to write :

echo "The contract will expire in" . $delay;

And the output would be :

The contract will expire in 3 days.

thanks for your help.

Nicolas Charvoz
  • 1,509
  • 15
  • 41
  • Already answered : [How do I compare two DateTime objects in PHP 5.2.8?](http://stackoverflow.com/questions/961074/how-do-i-compare-two-datetime-objects-in-php-5-2-8) – ThinkTank Oct 15 '15 at 13:31
  • I don't see how this is an answer to my problem .. – Nicolas Charvoz Oct 15 '15 at 13:34
  • 1
    You need to compare `strtotime($row['end_date'])` to `time()`, that gives you the seconds between them, then convert that to days – Adam Oct 15 '15 at 13:37
  • [DateTime](http://php.net/manual/fr/class.datetime.php) is usefull for Date & Time comparison and manipulation. Check the doc. – ThinkTank Oct 15 '15 at 13:44

1 Answers1

1
$interval = strtotime($date1) - strtotime($row['end_date']); // ... or replace $date1

$delayInDays = floor($interval / (60 * 60 * 24));

echo "The contract will expire in: " . $delayInDays;

If you're interested in object-oriented way to achieve this, you can take a look at DateTime::diff method.

Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56