Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to get the count of months between two dates?

Tags:

date

php

Let's assume I have two dates in variables, like

$date1 = "2009-09-01"; $date2 = "2010-05-01"; 

I need to get the count of months between $date2 and $date1($date2 >= $date1). I.e. i need to get 8.

Is there a way to get it by using date function, or I have to explode my strings and do required calculations?

Thanks.

like image 798
Simon Avatar asked Nov 20 '10 15:11

Simon


People also ask

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

The DATEDIF function is designed to calculate the difference between dates in years, months, and days. There are several variations available (e.g. time in months, time in months ignoring days and years, etc.) and these are set by the "unit" argument in the function.

How do I calculate period between two dates in Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.

How do you calculate the number of days in a month between two dates?

This might be what you are looking for. Show activity on this post. Go to the first day of the next month, and subtract one day. That gives you the total number of days for the current month.


2 Answers

For PHP >= 5.3

$d1 = new DateTime("2009-09-01"); $d2 = new DateTime("2010-05-01");  var_dump($d1->diff($d2)->m); // int(4) var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8) 

DateTime::diff returns a DateInterval object

If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :

$d1 = "2009-09-01"; $d2 = "2010-05-01";  echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8 

But it's not very precise (there isn't always 30 days per month).

Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.

Edit: This code should be more precise if you can't use DateTime::diff or your RDBMS :

$d1 = strtotime("2009-09-01"); $d2 = strtotime("2010-05-01"); $min_date = min($d1, $d2); $max_date = max($d1, $d2); $i = 0;  while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {     $i++; } echo $i; // 8 
like image 188
Vincent Savard Avatar answered Oct 14 '22 14:10

Vincent Savard


Or, if you want the procedural style:

$date1 = new DateTime("2009-09-01"); $date2 = new DateTime("2010-05-01"); $interval = date_diff($date1, $date2); echo $interval->m + ($interval->y * 12) . ' months'; 

UPDATE: Added the bit of code to account for the years.

like image 44
Chuck Burgess Avatar answered Oct 14 '22 14:10

Chuck Burgess