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:
- PHP File Last Modified and Filesize (bytes to KB/MB)
- Find Time Between Two Dates in PHP
- UPDATED: Strip Off Characters from String Using PHP (substr)
- jQuery AJAX Loading – Display Images or Text Until Script is Finished (Part 2)
- How to Install SSL Certificate on a Subdomain within Plesk 9
