note 107592 added to datetime.modify

From: Date: Mon, 20 Feb 2012 14:34:57 +0000
Subject: note 107592 added to datetime.modify
Groups: php.notes 
Request: Send a blank email to php-notes+get-186237@lists.php.net to get a copy of this message
These functions makes sure that adding months or years always ends up in the month you would expect. Works for positive and negative values <?php $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'); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 95.209.237.6 ---- Manual Page -- http://www.php.net/manual/en/datetime.modify.php Edit -- https://master.php.net/note/edit/107592 Del: integrated -- https://master.php.net/note/delete/107592/integrated Del: useless -- https://master.php.net/note/delete/107592/useless Del: bad code -- https://master.php.net/note/delete/107592/bad+code Del: spam -- https://master.php.net/note/delete/107592/spam Del: non-english -- https://master.php.net/note/delete/107592/non-english Del: in docs -- https://master.php.net/note/delete/107592/in+docs Del: other reasons-- https://master.php.net/note/delete/107592 Reject -- https://master.php.net/note/reject/107592 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186237) next »