How to calculate the 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 between these two dates, which are in a string format, and how can I calculate? I used

date_diff($object, $object2)

but it expects two date objects, and I have dates in String format , After using, date_diffI get the following error

Message: an object of the DateInterval class cannot be converted to a string.

+4
source share
4 answers

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

+5
source

strtotime, .

<?php

$start = strtotime('2016-12-1');
$end = strtotime('2016-12-11');
$diffInSeconds = $end - $start;
$diffInDays = $diffInSeconds / 86400;
+2
$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
+2
source
$dnow = "2016-12-1";
$dafter = "2016-12-11";
$dnow=date_create($dnow);
$dafter=date_create($dafter);
$difference=date_diff($dnow,$dafter);
0
source

Source: https://habr.com/ru/post/1662500/


All Articles