Rahul Singh
Rahul Singh

Reputation: 1632

Count total month

I have to find total months between two dates in Unix timestamp formats. I want to create a PHP function for that. I've tried this:

get_total_month($startunixdate, $endunixdate) {
    $monthdiff = $endunixdate-$startunixdate;
    $monthdiff = $monthdiff / 60*60*24*31; 
    return $monthdiff;
}

Does this function consider leap years as well as month with 30 and 31 separately, or it will just count an approximate month?

Upvotes: 1

Views: 865

Answers (3)

pbotros1234
pbotros1234

Reputation: 87

In order to do this, use the DateTime class.

function get_total_month($start, $end) {

    // Create DateTime objects
    $dt1 = new DateTime($start);
    $dt2 = new DateTime($end);

    // Get DateInterval object representing difference between the two
    $diff = $dt1->diff($dt2); // OR: $diff = date_diff($dt1, $dt2);

    // Print the "months" out
    echo $diff->format("Difference: %R%m months"); // OR access $diff->m manually

Upvotes: 2

Bryan
Bryan

Reputation: 2211

Your answer is in this line;

$monthdiff = $monthdiff / 60*60*24*31

This will just count a month based on 31 days. The code divides the seconds by 60 to get the number of minutes, 60 again to get hours, 24 to get number of days, then it uses 31 as the length of a month.

This will result in an approximation of the number of months. For instance, if you take timestamps at the beginning and end of February (start of March), you will usually have a timestamp difference equivalent to 28 days (29 in a leap year). Dividing that by 31 will give you a fraction less than 1, since you are using 31 to represent a full month, when in reality a whole calendar month has passed.

Upvotes: 4

Robert Wilson
Robert Wilson

Reputation: 669

U can use PHP 5.3 datetime method.

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

Reference: PHP DateTime

Upvotes: 1

Related Questions