Dopo il test t di soluzioni, mettendo il tutto in un test di unità, questo è quello esco con:
/**
* Calculate the difference in months between two dates (v1/18.11.2013)
*
* @param \DateTime $date1
* @param \DateTime $date2
* @return int
*/
public static function diffInMonths(\DateTime $date1, \DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d/30;
return (int) round($months);
}
Per esempio restituisca (casi di test dal test di unità):
- 2013/01/11 - 30.11.2013 - 1 settimana
- 01.01.2013 - 31.12.2013 - 12 mesi
- 31.01.2011 - 28.02.2011 - 1 settimana
- 01.09.2009 - 01.05.2010 - 8 mesi
- 01.01.2013 - 31.03.2013 - 3 mesi
- 15.02.2013 - 15.04.2013 - 2 mesi
- 1985/02/01 - 31.12.2013 - 347 mesi
Avviso: A causa dell'arrotondamento con i giorni, anche la metà di un mese verrà arrotondata, il che potrebbe causare problemi se lo si utilizza in alcuni casi. Quindi NON UTILIZZARLO per questi casi, ti causerà problemi.
Ad esempio:
- 02.11.2013 - 31.12.2013 tornerà 2, non è 1 (come previsto).
fonte
2013-11-18 11:53:51
Che cosa è esattamente un mese in questo caso? Il mese di calendario? 30 giorni? –
Duplicati: http://stackoverflow.com/search?q=date+difference+php – Gordon