2017-01-17 110 views
1

之間的差異計算函數我的目標是計算包括開始月份在內的兩個日期之間的月數。日期時間(月)

我正在使用此函數進行計算。

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; 
} 

在大多數情況下,精品工程,但是當函數的參數,例如:

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

函數返回:

15 

應該是16。我錯過了什麼?我在Stackoverflow上進行過研究,嘗試過提供的代碼的各種實現,但問題仍然存在。

謝謝。

+0

在結果中加1就是16 then,。, –

+0

爲什麼應該是16? ('2015-11';'2015-12';'2016-01';'2016-02';'2016-03';'2016-04';'2016-05';'2016-06';'' 2016-07';'2016-08';'2016-09';'2016-10';'2016-11';'2016-12';'2017-01' is __15__ months) –

+0

爲什麼'$ begin = new DateTime(date('Ym-d',strtotime($ date1)));'?爲什麼不簡單地'$ begin = new DateTime($ date1);'? –

回答

0

問題是用戶會設置項目的開始和結束日期。我需要爲項目將要設置的每個月創建一個輸入。所以在這種情況下我需要號碼16

感謝意見,我意識到DateTime::diff()在滿足幾年,幾個月和幾天的全部單位。

我解決了我的問題,將開始和結束日期設置爲本月的第一天。所以現在我的函數返回包括開始和結束月份在內的兩個日期之間的月數。

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; 
} 
0
11-04 to 12-04 = 1 month. 
12-04 to 01-04 = 1 month. 
01-04 to 02-01 = 0 month. 
Result diff->format('%m') = 2. 

($ DIFF->格式( '%Y')* 12)+ $ DIFF->格式( '%M')+ 1 = 1×12 + 2 + 1 = 15; 這是真的。

相關問題