Skip to content

Instantly share code, notes, and snippets.

@Athihusky
Created March 10, 2015 15:25
PHP Date-Function to add Calendar-Month to a specified Date and can handle leap years
<?php
function add_month($startdate,$month) {
$anyDate = date("Y-m-d",strtotime($startdate . " +1 days"));
$nextDate = date("Y-m-d",strtotime($anyDate . " +".$month." month"));
$checkDate = date("Y-m-d",strtotime($nextDate . " -".$month." month"));
if($anyDate != $checkDate){
list($yr,$mn,$da) = split('-',$anyDate); // separate date
$mn = $mn + $month;
$timestamp = mktime(0,0,0,$mn,1,$yr);
list($y,$m,$t) = split('-',date('Y-m-t',$timestamp));
$lastDay = date('Y-m-d',mktime(0,0,0,$m,$t,$y));
$return = $lastDay;
}
else $return = date("Y-m-d",strtotime($nextDate . " -1 days"));
return $return;
}
//Example use:
echo add_month('2015-01-31',1); // Will retun "2015-02-28"
echo add_month('2015-02-28',1); // Will retun "2015-03-31"
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment