使用闰年的php中两个日期之间的差异

我想从 php 中的两个日期中获取总月份数。我在互联网上到处搜索了两个日期之间的闰年计算,但没有找到答案。


如果我的输入是“2019-01-01”到“2019-03-31”,那么我预期的结果是 3 个月,但我得到的结果是 2 个月。


以下是我的代码。


 $date1 = strtotime("2019-01-01");  

 $date2 = strtotime("2019-02-28");  


 $diff = abs($date2 - $date1);  

 $years = floor($diff / (365*60*60*24));  

 $months = floor(($diff - $years * 365*60*60*24) 

                           / (30*60*60*24));  


 printf("%d months",$months);  

我哪里错了


婷婷同学_
浏览 158回答 3
3回答

慕森王

我理解你的问题..实际上你得到的结果是正确的,因为一天在晚上 12 点结束,你在白天检查。所以直到一天结束你才能得到完整的月份。如果你添加一天并检查你会得到正确的3个月下面我对您的代码进行了一些更改。$new_date = date('Y-m-d', strtotime('2019-02-28' . ' +1 day'));$date1 = strtotime("2019-01-01");  $date2 = strtotime($new_date);  $diff = abs($date2 - $date1);  $years = floor($diff / (365*60*60*24));  $months = floor(($diff - $years * 365*60*60*24)                        / (30*60*60*24));  printf("%d months",$months);  你也可以通过Mysql查询到服务器来获取SELECT TIMESTAMPDIFF(MONTH, '2019-01-01', (SELECT DATE_ADD('2019-02-28', INTERVAL 1 DAY))) as month你可以试试。希望它有帮助。

慕哥6287543

您必须在 $month 变量中添加额外的月份 $date1 = strtotime("2019-01-01");   $date2 = strtotime("2019-03-31");   $diff = abs($date2 - $date1);   $years = floor($diff / (365*60*60*24));   $months = floor(($diff - $years * 365*60*60*24)                            / (30*60*60*24)) +1 ;   printf("%d months",$months); //Output : give add one extra或者$date1 = date_create('2019-01-01');$date2 date_create('2019-03-31');$interval= date_diff($date1, $date1);echo $interval->format('%m months');
打开App,查看更多内容
随时随地看视频慕课网APP