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!)
@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