0

I used php strtotime function in my project and it was working fine, but today a user reported an issue, i checked and found strtotime function not giving correct output. My Code is:

echo date('M Y', strtotime('-1 month'));

It is giving output:

Mar 2017 instead of Feb 2017

I checked above code at code online tools and it is giving same output there, So is it php core function issue or i did some mistake? Note: I checked following code online

echo date('Y-m-d', strtotime('-1 month'));

Its output strange me which is

2017-03-02
Imran Qamer
  • 2,253
  • 3
  • 29
  • 52

1 Answers1

1
date("M Y", strtotime("-1 months"));

This is true but today is 30th March that's why you are not getting exact result which you want. So, we should use 1st day of month and then apply substraction.

Maya Shah
  • 950
  • 7
  • 17
  • 1
    Check this http://stackoverflow.com/questions/5760262/php-adding-months-to-a-date-while-not-exceeding-the-last-day-of-the-month – Maya Shah Mar 30 '17 at 06:42
  • Got answer from question suggested by hanky that is http://stackoverflow.com/questions/9058523/php-date-and-strtotime-return-wrong-months-on-31st – Imran Qamer Mar 30 '17 at 06:44
  • i needed to add this line before code $base = strtotime(date('Y-m',time()) . '-01 00:00:01'); and then by using this variable in second parameter of strtotime function it solved problem. – Imran Qamer Mar 30 '17 at 06:45
  • 1
    Yes exactly, If we search in stackoverflow itself we will have many question and answer similar to this issue. – Maya Shah Mar 30 '17 at 06:46