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.

Similar Posts:

3 thoughts on “Fixing strtotime -1 month”

  1. Hello,
    just got this problem with -1 month. i’ve used something different: date(‘Y-m’, strtotime(“-“.date(‘d’).” days”)).
    In my application i only needed Year and month.

  2. Yes, you can absolutely use strtotimefix(‘+1 month’) because if the problem happens at +1 month, then it will happen with -1 month as well, so the function will work the same way. You don’t want to arbitrarily choose +3 weeks, because that just won’t work in the long run.

  3. I found the same problem, where I was running this on 2009-10-31 and asking for date(‘Y-m-01’, strtotime(‘+ 1 month’)) gave me 2009-12-01. For me, because ’01’ for the day, I used ‘+ 3 weeks’ instead of ‘+ 1 month’.

Comments are closed.