linein designs

01 Apr, 2010

Find Years and Months Between Two Dates in PHP

Posted by: john In: php|programing|tutorial

This is an addition to the Find Time Between Two Dates in PHP post.

Here is a quick way to find the years and months between two dates using PHP. The dates are not exact since we’re assuming that each year and month has the same number of seconds.

function yearMonthDifference($start_date, $end_date)
{
	// 31556926 seconds in year
	$years = floor(($end_date - $start_date) / 31556926);
	// takes remaning seconds to find months  2629743.83 seconds each month
	$months = floor((($end_date - $start_date) % 31556926) / 2629743.83); 

	if($years > 0){
		if($years > 1){$year_s = 's';} // adds "s" if more than one year
		$years_display = $years.' year'.$year_s;
	}
	if($months > 0){
		if($months > 1){$month_s = 's';} // adds "s" if more than one month
		$months_display = $months.' month'.$month_s;
	}

	return trim($years_display.' '.$months_display);
}

// useage
$start_date = 'January 4, 2008';
$end_date = 'March 5, 2010';
echo yearMonthDifference($start_date,$end_date);

If you really want to get fancy, you may want to add a check to make sure the start date is less than the end date. Please post a comment below if you have any questions or suggestions.

Similar Posts:

2 Comments »

Comment by Joshua Kramer

The number of seconds in a year is not fixed… you are not considering leap conditions.

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post


  • Seren: Thanks - google did not fail me in finding this snippet (after 2 hours of 'why isn't this working!' before I choose to look for answers. That select
  • zdenis: type your scp command with nohup at the beginning: >nohup scp... enter your password stop temporarily the command with CTRL+z put on b
  • Criz: php script >> How to get the number of hours and minutes of a two set of time like this sample. 1st set of time : 8:00 to 17:00 2nd set of


Please Support Our Friends

Banner
FreshBooks

About

My name is John Veldboom and have been in design and web programing for just over 8 years now. Started off as a hobby in high school but it has developed into a full time job now. I always tell people that if I wasn't doing this at work each day, I would be at home doing it for free. I love it!

Please visit the contact page to drop me a message.