Skip to content

Instantly share code, notes, and snippets.

@BrainFeeder
Created February 6, 2017 10:47
Show Gist options
  • Save BrainFeeder/143d8bfe20883b7d0dff7d988cba755b to your computer and use it in GitHub Desktop.
Save BrainFeeder/143d8bfe20883b7d0dff7d988cba755b to your computer and use it in GitHub Desktop.
Administrative way of adding and substracting months in PHP
<?php
// FUNCTION 1 (without leap check?)
//////////////////////////////////////
$date=new DateTime();
$date->setDate(2008,2,29);
function addMonths($date,$months){
$init=clone $date;
$modifier=$months.' months';
$back_modifier =-$months.' months';
$date->modify($modifier);
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
while($init->format('m')!=$back_to_init->format('m')){
$date->modify('-1 day') ;
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
}
/*
if($months<0&&$date->format('m')>$init->format('m'))
while($date->format('m')-12-$init->format('m')!=$months%12)
$date->modify('-1 day');
else
if($months>0&&$date->format('m')<$init->format('m'))
while($date->format('m')+12-$init->format('m')!=$months%12)
$date->modify('-1 day');
else
while($date->format('m')-$init->format('m')!=$months%12)
$date->modify('-1 day');
*/
}
function addYears($date,$years){
$init=clone $date;
$modifier=$years.' years';
$date->modify($modifier);
while($date->format('m')!=$init->format('m'))
$date->modify('-1 day');
}
}
addMonths($date,-1);
addYears($date,3);
echo $date->format('F j,Y');
// FUNCTION 2 (with leap check?)
//////////////////////////////////////
$d = new DateTime('2007-12-31');
function addMonths($date, $months)
{
$years = floor(abs($months / 12));
$leap = 29 <= $date->format('d');
$m = 12 * (0 <= $months?1:-1);
for ($a = 1;$a < $years;++$a) {
$date = addMonths($date, $m);
}
$months -= ($a - 1) * $m;
$init = clone $date;
if (0 != $months) {
$modifier = $months . ' months';
$date->modify($modifier);
if ($date->format('m') % 12 != (12 + $months + $init->format('m')) % 12) {
$day = $date->format('d');
$init->modify("-{$day} days");
}
$init->modify($modifier);
}
$y = $init->format('Y');
if ($leap && ($y % 4) == 0 && ($y % 100) != 0 && 28 == $init->format('d')) {
$init->modify('+1 day');
}
return $init;
}
function addYears($date, $years)
{
return addMonths($date, 12 * $years);
}
echo $d->format('F j,Y') . ' N<br />';
$d = addMonths($d, +1);
echo $d->format('F j,Y') . ' +1M<br />';
$d = addMonths($d, +1);
echo $d->format('F j,Y') . ' +1M<br />';
$d = addYears($d, +60);
echo $d->format('F j,Y') . ' +60Y<br />';
$d = addYears($d, -59);
echo $d->format('F j,Y') . ' -59Y<br />';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment