错误查找2个日期之间的天数

时间:2014-03-01 03:28:29

标签: php

我试图找出1970年之前的两个日期之间的天数,

$ref = strtotime("1776-08-08");
$date = strtotime("1968-12-07");

$day_diff =floor(($date - $ref)/(60*60*24));

echo $day_diff;


// output i got:
-390

//should be 
70247

2 个答案:

答案 0 :(得分:3)

来自the manual for strtotime()

  

时间戳的有效范围通常是从星期五,1901年12月13日20:45:54 UTC到星期二,2038年1月19日03:14:07 UTC。 (这些是与32位有符号整数的最小值和最大值相对应的日期。)此外,并非所有平台都支持负时间戳,因此您的日期范围可能不会早于Unix时期。这意味着,例如1970年1月1日之前的日期不适用于Windows,某些Linux发行版和一些其他操作系统。 PHP 5.1.0和更新的版本克服了这个限制。

这意味着strtotime()将不适用于1901年12月13日最佳和1970年1月1日最差之前的日期。幸运的是PHP提供了一个解决方案。您可以将DateTime()用于strtotime()功能之外的日期:

$date1 = new DateTime('1776-08-08');
$date2 = new DateTime('1968-12-07');
$interval = $date1->diff($date2);
echo $interval->format('%a days'); // 70247

See it in action

答案 1 :(得分:2)

strtotime函数期望给出一个包含英文日期格式的字符串,并尝试将该格式解析为Unix时间戳(自1970年1月1日00:00:00 UTC以来的秒数),相对到现在给出的时间戳,或者如果现在没有提供当前时间。

http://in2.php.net/strtotime

您应该使用DateTime类而不是strtotime函数

注意:DateTime课程将有效>=5.2.0

$ref = new DateTime("1776-08-08");
$date = new DateTime("1968-12-07");

$diff = $ref->diff($date);

echo $diff->format('%a');

OR表示完整对象

print_r($diff)
相关问题