从2个时间戳开始的月份


Months from 2 unixtimestamps

我有两个日期的时间戳:2012年1月和2013年2月。这些时间戳之间的差值为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

使用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。演示