Skip to content

Instantly share code, notes, and snippets.

@koffisani
Last active May 9, 2017 10:07
Show Gist options
  • Save koffisani/4fd37f72c3fdf80a2e94066394e5518a to your computer and use it in GitHub Desktop.
Save koffisani/4fd37f72c3fdf80a2e94066394e5518a to your computer and use it in GitHub Desktop.
Adds months to a date without skipping february
<?php
/* As inspired by http://stackoverflow.com/a/10734891/3156582 */
$date = '2017-01-31';
$nbremois = -13;
$d1 = DateTime::createFromFormat('Y-m-d', $date);
$year = $d1->format('Y');
$month = $d1->format('m');
$day = $d1->format('d');
$year += $nbremois >= 0 ? floor($nbremois / 12) : ceil($nbremois/12);
//$year += floor($nbremois / 12);
$nbremois = $nbremois % 12;
$month += $nbremois;
//echo $month%12 + 12;
if( $month > 12 ) {
$year ++;
$month = $month % 12;
if( $month === 0 ) {
$month = 12;
}
}
if( $month < 0 ) {
$month = 12 + $month % 12;
$year--;
}
if( !checkdate($month, $day, $year) ) {
$d2 = DateTime::createFromFormat('Y-m-d', $year . '-' . $month . '-1');
$d2->modify('last day of');
} else {
$d2 = DateTime::createFromFormat('Y-m-d', $year . '-' . $month . '-' . $day);
}
echo $d2->format('Y-m-d');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment