Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the number of months between two dates in PHP?

Tags:

date

php

Without using PHP 5.3's date_diff function (I'm using PHP 5.2.17), is there a simple and accurate way to do this? I am thinking of something like the code below, but I don't know how to account for leap years:

$days = ceil(abs( strtotime('2000-01-25') - strtotime('2010-02-20') ) / 86400); $months = ???; 

I'm trying to work out the number of months old a person is.

like image 672
cronoklee Avatar asked Nov 16 '12 12:11

cronoklee


People also ask

How can I get the difference between two dates in php?

PHP date_diff() Function $date2=date_create("2013-12-12"); $diff=date_diff($date1,$date2);

How do I calculate the number of weeks between two dates in php?

php function week_between_two_dates($date1, $date2) { $first = DateTime::createFromFormat('m/d/Y', $date1); $second = DateTime::createFromFormat('m/d/Y', $date2); if($date1 > $date2) return week_between_two_dates($date2, $date1); return floor($first->diff($second)->days/7); } $dt1 = '1/1/2014'; $dt2 = '12/31/2014'; ...

How can we know the number of days between two given dates using php?

The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.


1 Answers

$date1 = '2000-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);  $diff = (($year2 - $year1) * 12) + ($month2 - $month1); 

You may want to include the days somewhere too, depending on whether you mean whole months or not. Hope you get the idea though.

like image 129
deceze Avatar answered Sep 30 '22 14:09

deceze