如何使用PHP找到两个日期之间的天数?
当前回答
// Change this to the day in the future
$day = 15;
// Change this to the month in the future
$month = 11;
// Change this to the year in the future
$year = 2012;
// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);
echo "There are $days days until $day/$month/$year";
其他回答
选择的答案不是最正确的答案,因为它将在UTC之外失败。 根据时区(列表),可能会有时间调整创建“没有”24小时的日子,这将使计算(60*60*24)失败。
这里有一个例子:
date_default_timezone_set('europe/lisbon');
$time1 = strtotime('2016-03-27');
$time2 = strtotime('2016-03-29');
echo floor( ($time2-$time1) /(60*60*24));
^-- the output will be **1**
因此,正确的解决方案是使用DateTime
date_default_timezone_set('europe/lisbon');
$date1 = new DateTime("2016-03-27");
$date2 = new DateTime("2016-03-29");
echo $date2->diff($date1)->format("%a");
^-- the output will be **2**
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
上面的代码用的很简单。谢谢。
看看所有的答案,我写了一个通用函数,适用于所有的PHP版本。
if(!function_exists('date_between')) :
function date_between($date_start, $date_end)
{
if(!$date_start || !$date_end) return 0;
if( class_exists('DateTime') )
{
$date_start = new DateTime( $date_start );
$date_end = new DateTime( $date_end );
return $date_end->diff($date_start)->format('%a');
}
else
{
return abs( round( ( strtotime($date_start) - strtotime($date_end) ) / 86400 ) );
}
}
endif;
一般来说,我使用“DateTime”来查找两个日期之间的天数。但如果出于某种原因,一些服务器设置没有启用'DateTime',它将使用'strtotime()'简单(但不安全)计算。
PHP中两个日期之间的天数
function dateDiff($date1, $date2) //days find function
{
$diff = strtotime($date2) - strtotime($date1);
return abs(round($diff / 86400));
}
//start day
$date1 = "11-10-2018";
// end day
$date2 = "31-10-2018";
// call the days find fun store to variable
$dateDiff = dateDiff($date1, $date2);
echo "Difference between two dates: ". $dateDiff . " Days ";
从PHP 5.3及以上版本开始,添加了新的日期/时间函数来获得不同:
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
结果如下:
Difference: 1 years, 0 months, 2 days
DateInterval Object
(
[y] => 1
[m] => 0
[d] => 2
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 367
)
希望能有所帮助!
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PowerShell格式化日期时间
- 如何在PHP中获得变量名作为字符串?
- 在c#中解析字符串为日期时间
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 如何在Python中获取UTC时间?
- 在PHP中对动态变量名使用大括号