如何使用PHP找到两个日期之间的天数?
当前回答
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
上面的代码用的很简单。谢谢。
其他回答
如果你有以秒为单位的时间(即unix时间戳),那么你可以简单地减去时间并除以86400(秒/天)
看看所有的答案,我写了一个通用函数,适用于所有的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()'简单(但不安全)计算。
// 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";
使用这个简单的函数。声明函数
<?php
function dateDiff($firstDate,$secondDate){
$firstDate = strtotime($firstDate);
$secondDate = strtotime($secondDate);
$datediff = $firstDate - $secondDate;
$output = round($datediff / (60 * 60 * 24));
return $output;
}
?>
像这样调用这个函数
<?php
echo dateDiff("2018-01-01","2018-12-31");
// OR
$firstDate = "2018-01-01";
$secondDate = "2018-01-01";
echo dateDiff($firstDate,$secondDate);
?>
这个工作!
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
推荐文章
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 从IP地址获取位置
- 在c#中创建一个特定时区的DateTime
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?
- 当使用Composer的开发/生产开关时,如何正确部署?
- 自动删除Laravel (Eloquent ORM)中的相关行
- 如何减去X天从一个日期对象在Java?