Fixing strtotime -1 month

There is a bug for strtotime() when you are on the last day of a month that has 31 days in it. The function, strotime(‘-1 month’) will return the beginning of the current month, or put another way, 30 days prior. Needless to say, this is annoying. However, it doesn’t come up very often, and there is a way to fix things: by rolling back the clock 3 extra days. I ran into this problem on a different personal project, and wrote the following function to address the issue. Whenever using strtotime() and negative months, switch in strtotimefix() instead:

function strtotimefix($val,$timestamp=0){
	if ($timestamp==0){ $timestamp = time(); }
	if (date('m') == date('m',strtotime('-1 month'))){
		$timestamp = strtotime('-3 days',$timestamp);
	}else{
		if($timestamp==0){$timestamp = time();}
	}
	$strtotime = strtotime($val,$timestamp);
	return $strtotime;
}

So what’s happening? Basically, the function will check if the numeric month is the same between the current month and the month through ‘-1 month’. If so, it subtracts 3 days from the current timestamp, then runs through the strtotime function using the new timestamp. If everything is fine, nothing is altered, so you don’t have to worry that using the strtotimefix() function will break a perfectly normal strtotime(‘-1 month’) call. Be advised that if you are not doing a call with ‘-x month’, the function will return an incorrect timestamp by 3 days (I hope to update it to be self-aware and only ‘fix’ when the bug would be introduced).

Updated on March 30, 2010:
Changed it to -3 days to deal with February/March.