note 117600 added to datetime.modify

From: Date: Sat, 04 Jul 2015 20:31:33 +0000
Subject: note 117600 added to datetime.modify
Groups: php.notes 
Request: Send a blank email to php-notes+get-203045@lists.php.net to get a copy of this message
This is an improvement of @jenspj's answer <?php $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 />'; ---- Server IP: 72.52.91.14 Probable Submitter: 177.135.18.195 ---- Manual Page -- http://php.net/manual/en/datetime.modify.php Edit -- https://master.php.net/note/edit/117600 Del: integrated -- https://master.php.net/note/delete/117600/integrated Del: useless -- https://master.php.net/note/delete/117600/useless Del: bad code -- https://master.php.net/note/delete/117600/bad+code Del: spam -- https://master.php.net/note/delete/117600/spam Del: non-english -- https://master.php.net/note/delete/117600/non-english Del: in docs -- https://master.php.net/note/delete/117600/in+docs Del: other reasons-- https://master.php.net/note/delete/117600 Reject -- https://master.php.net/note/reject/117600 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203045) next »