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:

1 Comment »

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


  • john: There's no easy way to stop it within the InnerFade plugin, but you could just erase all the list items after you've cycled through them using jQuery.
  • Steven: Rachid, did you find an answer? Is there a way to stop by a picture at the end? Can anyone help? Thanks in advance!
  • htc smartphone: WP togo is going to be a great little example of just what kind of super-power these droids will offer like the htc aria and other htc mobile phones l


Please Support Our Friends

Send emails with ease on this SMTP server by JangoSmtp.com.

Banner

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.