Skip to content

Instantly share code, notes, and snippets.

@garak
Created May 31, 2011 07:45
Show Gist options
  • Save garak/1000118 to your computer and use it in GitHub Desktop.
Save garak/1000118 to your computer and use it in GitHub Desktop.
never use '+1 month' and '-1 month' in strtotime. It's just bugged
<?php
// tried this today, 31 May 2011
echo "\n";
echo date('Y-m-d', strtotime('first day of next month')); // correct
echo "\n";
echo date('Y-m-d', strtotime('+1 month')); // wrong! output is 2011-07-01
echo "\n";
echo date('Y-m-d', strtotime('next month')); // as above, output is 2011-07-01
echo "\n";
echo date('Y-m-d', strtotime('first day of previous month')); // correct
echo "\n";
echo date('Y-m-d', strtotime('-1 month')); // wrong! output is 2011-05-01
echo "\n";
echo date('Y-m-d', strtotime('2011-05-29 first day of previous month')); // correct (nice!)
@jakuza
Copy link

jakuza commented May 31, 2011

That behavior is perfectly expected when moving 1 month back/ahead from a 31-days month over 30-days month.

@garak
Copy link
Author

garak commented May 31, 2011

@jakuza: I think it's not expected, at least not for everyone. If the aim of strtotime() is using natural language, "next month" and "previous month" should be clear enough: I want next (previous) month, no matter how long months are.

@wdog
Copy link

wdog commented Mar 7, 2016

I agree with @garak this is strage beaviour, it breaks the intention of naturally speaking language with dates, and is not consistent

look at this example

echo date('d/m/Y', strtotime('2011-05-31 first day of +1 month')); //  returns  01/06/2011

(Yes I know that first it gets the 01 of current month and then adds 1 month)

@DazWilliams
Copy link

If you only need the Year and Month, this is better at skipping ahead / back by X months even on the 31st

date("M-y", mktime(0, 0, 0, date("m")-$i, 1, date("Y")));

@deathemperor
Copy link

This bug still exists in php 7.0

Thanks DazWilliams for the quick fix.

@jameswebbdesign
Copy link

jameswebbdesign commented Mar 31, 2021

Does this still work in December when adding a month? @DazWilliams

@DazWilliams
Copy link

DazWilliams commented Mar 31, 2021

Does this still work in December when adding a month? @DazWilliams

It sure does James.

You can see it here:
https://extendsclass.com/php-bin/e5145f2

$i=1;

echo date("M-y", mktime(0, 0, 0, 12+$i, 1, date("Y")));

Output: Jan-22

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment