2010-08-13 168 views
3

您將如何計算兩個任意日期之間的月數?鑑於即使一個月只有一天,它也被視爲整整一個月。計算日期之間的月份數量

實例:

  • 2010-01-01 - 2010-03-31 =3個月
  • 2010-06-15 - 2010-09-01 =4個月

等等。我想把時間戳的差異與2592000(一個月內的平均秒數)相區別,但看起來很拙劣,容易出錯。我想盡可能快地保持它(需要快速運行數千次),所以我想用strtotime也不是最優的?

回答

7

如果我正確閱讀你的問題,你會想在1月31日和2月1日返回「2」,因爲它跨越了1月和2月,儘管它們只相隔1天。

你可以工作了(僞代碼):

monthno1 = (date1_year * 12) + date1_month; 
monthno2 = (date2_year * 12) + date2_month; 

return (monthno2 - monthno1) + 1; 

這假定第二個日期後的日期。

+1

是啊,這似乎正確地做到這一點,謝謝! – 2010-08-13 06:49:35

+0

是的。謝謝。 – 2012-11-09 11:20:54

1

假設日期是在一個已知的格式:

function getMonths($start, $end) { 
    $startParsed = date_parse_from_format('Y-m-d', $start); 
    $startMonth = $startParsed['month']; 
    $startYear = $startParsed['year']; 

    $endParsed = date_parse_from_format('Y-m-d', $end); 
    $endMonth = $endParsed['month']; 
    $endYear = $endParsed['year']; 

    return ($endYear - $startYear) * 12 + ($endMonth - $startMonth) + 1; 
} 

這給:

print(getMonths('2010-01-01', '2010-03-31')); // 3 
print(getMonths('2010-06-15', '2010-09-01')); // 4 
相關問題