duanliaogui4133 2017-01-17 10:04
浏览 190
已采纳

日期时间(月)之间差异计算的功能

my goal is to calculate the number of months between two dates including the starting month.

I am using this function to calculate.

function number_months($date1, $date2){
    $begin = new DateTime(date('Y-m-d', strtotime($date1)));
    $end = new DateTime(date('Y-m-d', strtotime($date2)));

    $diff = $end->diff($begin);
    return ($diff->format('%y') * 12) + $diff->format('%m') + 1;
}

In most cases in works fine, but when the function parameters are for example:

$date1 = 2015-11-04 00:00:00
$date2 = 2017-02-01 00:00:00

Function returns:

15

Should be 16. What am I missing? I did reseach here on Stackoverflow, have tried various implementations of provided code, but the problem still ocurs.

Thanks.

  • 写回答

2条回答 默认 最新

  • douxiawei9318 2017-01-17 12:02
    关注

    The problem is that the user will set the start and end date of project. And I need to create a input for every month the project is going to be set. So i need number 16 in this case.

    Thanks to comments i realised that DateTime::diff() works in full units when it comes to years, months and days.

    I solved my problem by setting the start and end date to 1st of the month. So now my function returns number of months between two dates including starting and ending month.

    function number_months($date1, $date2){
        $begin = new DateTime(date('Y-m-d', strtotime($date1)));
        $end = new DateTime(date('Y-m-d', strtotime($date2)));
    
        $begin->modify('first day of this month')->setTime(12, 00);
        $end->modify('first day of this month')->setTime(12, 00);
    
        $diff = $end->diff($begin);
        return ($diff->format('%y') * 12) + $diff->format('%m') + 1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画