note 113140 deleted from datetime.formats.relative by derick
| From: | derick@php.net | Date: | Fri, 01 Dec 2017 10:46:06 +0000 |
| Subject: | note 113140 deleted from datetime.formats.relative by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-209286@lists.php.net to get a copy of this message | ||
Note Submitter: shkkmo at gmail dot com
----
Here is a fairly simple function I wrote to avoid the issues with adding/subtracting months that has
been mentioned by cristinawithout and many others.
I needed this function to be able handle monthly billing cycles properly. It handles positive and
negative values for months. It also can be used to side step a similar issues for adding years on
leap days (e.g. strtotime('2012/2/29 +1 year') by passing in multiples of 12 (e.g.
addMonthsToTime(12, strtotime('2012/2/29'))
<?
function addMonthsToTime($numMonths = 1, $timeStamp = null){
$timeStamp === null and $timeStamp = time();//Default to the present
$newMonthNumDays = date('d',strtotime('last day of '.$numMonths.'
months', $timeStamp));//Number of days in the new month
$currentDayOfMonth = date('d',$timeStamp);
if($currentDayOfMonth > $newMonthNumDays){
$newTimeStamp = strtotime('-'.($currentDayOfMonth - $newMonthNumDays).' days
'.$numMonths.' months', $timeStamp);
} else {
$newTimeStamp = strtotime($numMonths.' months', $timeStamp);
}
return $newTimeStamp;
}
?>