0

I'm sorry to ask such a basic question but this has been stumping me and I'm sure its got to be something simple.

All I want to be able to do is work out the number of days diference, as an interger between a field that an earlier part of my code retrieves, and the current date.

The code that gets my expiry date is $data100["ExpiryDate"], and I know that this works because when I echo, I get

2018-04-23

All I want is to figure out how to calculate the difference between $data100["ExpiryDate"] and now() in terms of an interger, e.g. 45, so that i can then see if it is within 3 months for a later section of the code.

I have tried a few articles on here, and phpmanual, but keep getting errors like:

Object of class DateInterval could not be converted to string

Sorry forgot to include code, this is one example I have tried...

$date1 = new DateTime($data100["ExpiryDate"]);
$date2 = new DateTime("now");
$interval=date_diff($date1,$date2);

Have also tried this:

>       $interval = $datetime1->diff($datetime2);       echo
> $interval->format('%R%a days');

But dont want this option as I just want the output as an interger.

Solved it using this, thanks.

$date1 = new DateTime($data100["ExpiryDate"]);
$date2 = new DateTime("now");

$diff = $date2->diff($date1)->format("%a");

2 Answers2

0

If you just want the difference as an integer, you could retrieve the property d from the DateInterval class.

echo $interval->d; // 11

var_dump($interval)

object(DateInterval)#3 (15) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(11)
  ["d"]=>
  int(11)
  ["h"]=>
  int(10)
  ["i"]=>
  int(32)
  ["s"]=>
  int(43)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(1)
  ["days"]=>
  int(346)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
-1

This is what I use for getting the date difference

function dateDifference($date1, $date2 = NULL) {
    if(!$date2) {
        $date2 = date('Y/m/d H:i:s', time());
    }

    $date1 = new DateTime($date1);
    $date2 = new DateTime($date2);

    return $date2->diff($date1);
}

Where $date2 is the larger date (most recent). You can change it however you need it to work. This returns an object where you can get the difference of years/months/days. e.g.

dateDifference('2015-5-11')->y
dateDifference('2015-5-11')->m
dateDifference('2015-5-11')->d
DiddleDot
  • 745
  • 5
  • 16