PHP Date difference

倾然丶 夕夏残阳落幕 提交于 2019-12-12 10:36:53

问题


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.


回答1:


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));



回答2:


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




回答3:


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');



回答4:


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');
}



回答5:


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";


来源:https://stackoverflow.com/questions/15743882/php-date-difference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!