-1
$date1 = new DateTime("2012-12-15 14:11:42");
$date2 = new DateTime(date('Y-m-d H:i:s'));
$month =  $date1->diff(date('Y-m-d H:i:s'));
echo $month->m;

Instead of displaying the difference what i get is the warning below Warning: DateTime::diff() expects parameter 1 to be DateTime, string given in C:\xampp\htdocs\giftcodex\test.php on line 9

Notice: Trying to get property of non-object in C:\xampp\htdocs\giftcodex\test.php on line 10

Precious George
  • 105
  • 4
  • 8

3 Answers3

0

here is the mistake rather of giving it a string generated by date('Y-m-d H:i:s') give it a DateTime object $date2

$month =  $date1->diff($date2);
echo $month->format('%m')

check the docs here http://www.php.net/manual/en/datetime.diff.php

zzlalani
  • 22,960
  • 16
  • 44
  • 73
0

You should take a look at this from the PHP Manual.

The date_diff is a PHP feature which can help you in this regard, as given below.

$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%m months');
Ali Gajani
  • 14,762
  • 12
  • 59
  • 100
0

Method ->diff() will as first parameter accept DateTime object, not string.

Change:

$month =  $date1->diff(date('Y-m-d H:i:s'));

to:

$month =  $date1->diff($date2);

To get full month difference between 2 dates, you will also need to add years*12:

$date1  = new DateTime("2012-12-15 14:11:42");
$date2  = new DateTime("now");
$diff   = $date1->diff($date2);
$months = $diff->m + $diff->y * 12;
Glavić
  • 42,781
  • 13
  • 77
  • 107