如何使用PHP找到两个日期之间的天数?
当前回答
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 ";
其他回答
计算两个日期的差值:
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
输出: + 272天
函数的作用是:返回两个DateTime对象之间的差值。
我已经尝试了答案中几乎所有的方法。但是DateTime和date_create在所有测试用例中都没有给出正确答案。特别在2月和3月或12月和1月进行测试。
所以,我想出了混合溶液。
public static function getMonthsDaysDiff($fromDate, $toDate, $includingEnding = false){
$d1=new DateTime($fromDate);
$d2=new DateTime($toDate);
if($includingEnding === true){
$d2 = $d2->modify('+1 day');
}
$diff = $d2->diff($d1);
$months = (($diff->format('%y') * 12) + $diff->format('%m'));
$lastSameDate = $d1->modify("+$months month");
$days = date_diff(
date_create($d2->format('Y-m-d')),
date_create($lastSameDate->format('Y-m-d'))
)->format('%a');
$return = ['months' => $months,
'days' => $days];
}
我知道,性能方面这是相当昂贵的。你也可以把它扩展到年限。
如果你有以秒为单位的时间(即unix时间戳),那么你可以简单地减去时间并除以86400(秒/天)
易于使用date_diff
$from=date_create(date('Y-m-d'));
$to=date_create("2013-03-15");
$diff=date_diff($to,$from);
print_r($diff);
echo $diff->format('%R%a days');
详见:https://blog.devgenius.io/how-to-find-the-number-of-days-between-two-dates-in-php-1404748b1e84
// 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的json_encode函数转换UTF-8字符串为十六进制实体?
- 单元测试:日期时间。现在
- 如何从一个查询插入多行使用雄辩/流利
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 在mongodb中存储日期/时间的最佳方法
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- 在Android应用程序中显示当前时间和日期
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- PHP中的echo, print和print_r有什么区别?
- 如何转换日期时间?将日期时间
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 如何将python datetime转换为字符串,具有可读格式的日期?