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.

2

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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;

2 Comments

The code return difference time in second. You should convert it to day.
There are 86400 seconds in a day, so divide the result by this number.
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

Comments

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

Comments

-1
$dnow = "2016-12-1";
$dafter = "2016-12-11";
$dnow=date_create($dnow);
$dafter=date_create($dafter);
$difference=date_diff($dnow,$dafter);

2 Comments

Duplicate of @krunal answer.
You only changed variable name, but solution is same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.