Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of decimal months between two dates

Tags:

php

How do you find the number of decimal months between two dates in php?

I tried the code below:

$date1 = '2010-01-25';
$date2 = '2010-02-20';

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);

$month1 = date('m', $ts1);
$month2 = date('m', $ts2);

$day1 = date('d', $ts1);
$day2 = date('d', $ts2);

$diff = (($year2 - $year1) * 12) + ($month2 - $month1);

but it only gives me whole months. I want with decimals. Like 1.5 months or 1.4 months.

like image 612
Kermit the Frog Avatar asked Dec 04 '13 21:12

Kermit the Frog


People also ask

How do I calculate the difference between two dates and months in Excel?

Use the DATEDIF function when you want to calculate the difference between two dates. First put a start date in a cell, and an end date in another.

How do you find the number of months between two dates in SQL?

MONTHS_BETWEEN returns number of months between dates date1 and date2 . If date1 is later than date2 , then the result is positive. If date1 is earlier than date2 , then the result is negative.


2 Answers

First off use DateTime::diff to compare your dates. This will give you a DateInterval result object.

Then I would do something like this:

$months = ($interval->y * 12) + $interval->m; // Total number of whole months
$months += number_format($interval->d / 30, 1); // Add the month fraction

Working example: http://3v4l.org/f6n3r

like image 111
jszobody Avatar answered Nov 15 '22 08:11

jszobody


Dividing amount of days by 30 days is an easy implementation. It is not acceptable for sensitive calculations such as invoices or other finance related stuff.

There is an awesome DateTime extension called Carbon

$start = Carbon::create(2010, 1, 25, 0, 0, 0);
$end = Carbon::create(2010, 2, 20, 0, 0, 0);

echo $start->floatDiffInMonths($end); // "0.90437788018433"

It considers amount of days in a month, leap year and other things.

Keep in mind that calculation happens including time, so if you add 24 hours to $end, then 20 Feb 2010 will also be included:

$start = Carbon::create(2010, 1, 25, 0, 0, 0);
$end = Carbon::create(2010, 2, 20, 24, 0, 0);

echo $start->floatDiffInMonths($end); // "0.94009216589862"

It also supports daylight saving times in different timezones, for that, you'll need to use floatDiffInRealMonths

like image 24
alex23 Avatar answered Nov 15 '22 08:11

alex23