Home » Php » PHP Date difference

PHP Date difference

Posted by: admin July 12, 2020 Leave a comment

Questions:

i’ve the following code:

$dStart = new DateTime('2013-03-15');
$dEnd = new DateTime('2013-04-01');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->days;

I don’t know why i’m getting 6015 as result.

How to&Answers:

Try like

$dStart = strtotime('2013-03-15');
$dEnd = strtotime('2013-04-01');
$dDiff = $dEnd - $dStart;
echo date('H:i:s',$dDiff);

or as per your code try with

$dDiff = $dStart->diff($dEnd);
$date->format('d',$dDiff);
echo $dDiff->days;

if you want diff in days try with this also

echo floor($dDiff/(60*60*24));

Answer:

Try this-

$dStart = new DateTime('2013-03-15');
$dEnd = new DateTime('2013-04-01');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%d days')

Check PHP

Please check demo link

Answer:

use this

 $datetime1 = date_create('2013-03-15');
 $datetime2 = date_create('2013-04-01');
 $interval = date_diff($datetime1, $datetime2);
 echo $interval->format('%R%a days');

Answer:

I prefer something like:

function days_diff($first_date, $second_date)
{
    $later = new DateTime($second_date);
    $then = new DateTime($first_date);
    return $later->diff($then)->format('a');
}

Answer:

I got the same 6015 days on PHP 5.3.0 and found the solution using var_dump().
My exact code is here:

$timestring = "Thu, 13 Jun 2013 14:05:59 GMT";
date_default_timezone_set('GMT');
$date = DateTime::createFromFormat('D, d M Y G:i:s T', $timeString);
$nowdate = new DateTime("now");
$interval = $date->diff($nowdate);

Now if I do a var_dump($interval), the result is:

object(DateInterval)#5 (8) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(0)
  ["h"]=>
  int(19)
  ["i"]=>
  int(45)
  ["s"]=>
  int(33)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(6015)
}

So the hours (h), minutes(i) and seconds (s) are set correctly but there is another property days which remains constant at 6015 and this is what others are getting as a bug. Well, I can’t understand where it is getting this value. Again, as per the PHP manual for DateInterval at http://www.php.net/manual/en/class.dateinterval.php, I tried accessing them as properties of an object and things went absolutely fine.

Hence, I get exact result by:

echo (string) $interval->d." days ago";