Abhijit Kumbhar
Abhijit Kumbhar

Reputation: 961

How to calculate difference of two string dates in days using PHP?

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.

Upvotes: 11

Views: 9463

Answers (5)

Pikamander2
Pikamander2

Reputation: 8299

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

Upvotes: 0

Jerodev
Jerodev

Reputation: 33186

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;

Upvotes: 6

user6623857
user6623857

Reputation:

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

Upvotes: -1

user7234690
user7234690

Reputation:

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

Upvotes: 7

Aditya
Aditya

Reputation: 39

$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

Upvotes: 3

Related Questions