11

I have two date variables:

$dnow = "2016-12-1";
$dafter = "2016-12-11";

I want to calculate the difference of this two dates which are in string format so how do I calculate? I used

date_diff($object, $object2)

but it expecting two date object, and I have dates in String format , After using date_diff I get following error

Message: Object of class DateInterval could not be converted to string.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Abhijit Kumbhar
  • 923
  • 3
  • 23
  • 49
  • 2
    Possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Rav Dec 01 '16 at 08:09
  • 3
    Possible duplicate of [Finding the number of days between two dates](http://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates) – Mohammad Dec 01 '16 at 08:13

5 Answers5

7

Try this, use date_create

$dnow = "2016-12-1";
$dafter = "2016-12-11";
$date1=date_create($dnow);
$date2=date_create($dafter);
$diff=date_diff($date1,$date2);
print_r($diff);

DEMO

6

You could use the strtotime function to create a timestamp of both dates and compare those values.

<?php

$start = strtotime('2016-12-1');
$end = strtotime('2016-12-11');
$diffInSeconds = $end - $start;
$diffInDays = $diffInSeconds / 86400;
Jerodev
  • 32,252
  • 11
  • 87
  • 108
3
$datetime1=date_create($dnow);
$datetime2 = date_create($dafter);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
//%R is used to show +ive or -ive symbol and %a is used to show you numeric difference
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Aditya
  • 39
  • 5
0

If you just need the number of days, then you can use the DateInterval object's days property.

$day1 = '2016-12-1';
$day2 = '2016-12-11';
$days_elapsed = date_diff(date_create(date($day1)), date_create($day2)) -> days;

echo $days_elapsed; //Outputs 10
Pikamander2
  • 7,332
  • 3
  • 48
  • 69
-1
$dnow = "2016-12-1";
$dafter = "2016-12-11";
$dnow=date_create($dnow);
$dafter=date_create($dafter);
$difference=date_diff($dnow,$dafter);