machineaddict
machineaddict

Reputation: 3236

Months from 2 unixtimestamps

I have 2 timestamps from 2 dates: 01/2012 and 02/2013. The difference between these timestamps is 31795200. The function i've used is:

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

But there is a problem, the months are rounded to 30 days. What's the best way of calculating the months difference between them?

LE:

The solution suggested by a friend is:

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

i'm gonna use this. thanks @nickb

Upvotes: 0

Views: 56

Answers (1)

nickb
nickb

Reputation: 59709

Use PHP's DateTime class instead of UNIX timestamps:

$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);

Will output:

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

So, to calculate total months, we can do:

$months = $diff->y * 12 + $diff->m;

Which will print 13. Demo

Upvotes: 2

Related Questions