php 如何在php中减去两个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18396092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Minus two dates in php
提问by albert Daracan
i want to minus two dates in php
我想在 php 中减去两个日期
for example:
例如:
$date1 = 08/16/2013;
$date2 = 08/23/2013;
$answer = date2 - date1;
the $answer should be 7, How will i do that? thank you so much
$answer 应该是 7,我该怎么做?太感谢了
回答by Glavi?
Start using DateTimeclass for date/time manipulation :
开始使用DateTime类进行日期/时间操作:
$date1 = new DateTime('08/16/2013');
$date2 = new DateTime('08/23/2013');
$diff = $date1->diff($date2);
print_r($diff); // or $diff->days
Output :
输出 :
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 7
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 7
)
Read more for DateTime:diff().
Please note that various strtotime()examples are not correct in date/time difference calculation. The simplest example is difference between 2013-03-31 21:00
and 2013-03-30 21:00
. Which for naked eye is exact 1 day difference, but if you do subtract this 2 dates, you will get 82800
seconds which is 0.95833333333333
days. This is because of the time change from winter to summer time. DateTime handles leap years and time-zones properly.
请注意,各种strtotime()示例在日期/时间差计算中是不正确的。最简单的例子是2013-03-31 21:00
和之间的区别2013-03-30 21:00
。这对于肉眼来说正好是 1 天的差异,但是如果你减去这 2 个日期,你会得到82800
秒,也就是0.95833333333333
天。这是因为时间从冬季变为夏季。DateTime 正确处理闰年和时区。
回答by Chinmay235
Try this -
尝试这个 -
<?php
$date1 = strtotime('08/16/2013');
$date2 = strtotime('08/23/2013');
echo $hourDiff=round(abs($date2 - $date1) / (60*60*24),0);
?>
回答by Bora
You can get with strtotime
and minus dates
你可以得到strtotime
和减去日期
$diff = abs(strtotime('08/16/2013') - strtotime('08/23/2013'));
echo $min = floor($diff / (60*60*24)); // 7
回答by Yasitha
$date1 = '08/16/2013';
$date2 = '08/23/2013';
$days = (strtotime($date2) - strtotime($date1)) / (60 * 60 * 24);
print $days;