我有2个日期的2个时间戳:01/2012和02/2013。这些时间戳之间的差异是31795200.我使用的函数是:
function unixTimeStampInMonths($timestamp){
$elapsed_minutes = ($timestamp / 60);
$elapsed_hours = ($elapsed_minutes / 60);
$elapsed_days = ($elapsed_hours / 24);
$elapsed_months = floor($elapsed_days / 30);
return $elapsed_months;
}
但是有一个问题,这几个月会缩短到30天。计算它们之间月份差异的最佳方法是什么?
LE
朋友建议的解决方案是:
// arguments format: 05/2010
function monthDifferenceBetween2Dates($first, $second){
$expl1 = explode('/', $first);
$expl2 = explode('/', $second);
$months_in_years = ($expl2[1] - $expl1[1] - 1) * 12;
$first_months = 12 - $expl1[0];
$second_months = $expl2[0];
return $months_in_years + $first_months + $second_months;
}
我会用这个。谢谢@nickb
答案 0 :(得分:2)
使用PHP的DateTime类而不是UNIX时间戳:
$start = DateTime::createFromFormat( 'm/d/Y', '01/01/2012');
$end = DateTime::createFromFormat( 'm/d/Y', '02/01/2013');
$diff = $start->diff( $end);
var_dump( $diff);
将输出:
object(DateInterval)#3 (8) {
["y"]=>
int(1)
["m"]=>
int(1)
["d"]=>
int(0)
["h"]=>
int(0)
["i"]=>
int(0)
["s"]=>
int(0)
["invert"]=>
int(0)
["days"]=>
int(397)
}
因此,要计算总月数,我们可以这样做:
$months = $diff->y * 12 + $diff->m;
将打印13. Demo