Calculate the number of months between two dates in PHP?

前端 未结 12 1753
无人及你
无人及你 2020-12-01 05:12

Without using PHP 5.3\'s date_diff function (I\'m using PHP 5.2.17), is there a simple and accurate way to do this? I am thinking of something like the code below, but I don

12条回答
  •  悲哀的现实
    2020-12-01 06:10

    $date1 = '2000-01-25';
    $date2 = '2010-02-20';
    
    $ts1 = strtotime($date1);
    $ts2 = strtotime($date2);
    
    $year1 = date('Y', $ts1);
    $year2 = date('Y', $ts2);
    
    $month1 = date('m', $ts1);
    $month2 = date('m', $ts2);
    
    $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
    

    If Month switched from Jan to Feb above code will return you the $diff = 1 But if you want to consider next month only after 30 days then add below lines of code along with above.

    $day1 = date('d', $ts1);
    $day2 = date('d', $ts2);
    
    if($day2 < $day1){ $diff = $diff - 1; }
    

提交回复
热议问题