0
<?php
    $date = "20230730";
    $newdate = date("M-y", strtotime ( '-1 month' , strtotime ( $date ) )) ;
    echo $newdate;
?>

output: Jun-23

same we do with date 31 july :

<?php
    $date = "20230731";
    $newdate = date("M-y", strtotime ( '-1 month' , strtotime ( $date ) )) ;
    echo $newdate;
?>

output: Jul-23

  • Based on the days in the month how to find correct last month as the answer in this is coming wrong if days in the month are 31.

  • how to find same answer in PHP carbon library .

saurabh kamble
  • 1,510
  • 2
  • 25
  • 42
  • There is no June 31, it's converted to July 1. – Barmar Aug 01 '23 at 07:34
  • You could pass in `last day of previous month` in place of `-1 month`. – user3783243 Aug 01 '23 at 09:18
  • @Barmar that is the question its bug in php it is just subtracting 30 days without checking if the difference is 31 or 30 – saurabh kamble Aug 01 '23 at 11:44
  • 1
    @saurabhkamble See https://stackoverflow.com/questions/14584115/php-strtotime-1-month-adding-an-extra-month `20230731` becomes `20230631` which doesn't exist, the next valid date is `20230701`. – user3783243 Aug 01 '23 at 14:09
  • It's not considered a bug. When you subtract a month from a date, it means to go to the same day number in the previous month. If that day number doesn't exist, it has to find the equivalent date. They could have chosen to cap it, so July 31 goes to June 30, or they could have raised an exception, but they chose this result instead. – Barmar Aug 01 '23 at 15:17
  • Dates and times have lots of anomalies. For instance, no matter how you choose to resolve the add/subtract a month problem, date - 1 month + 1 month won't necessarily return to the original date. With the current design, 7/31 will become 8/1. If it capped to the end of June, 7/31 would become 7/30. – Barmar Aug 01 '23 at 15:20
  • @user3783243 how to make it move to 20230630 – saurabh kamble Aug 02 '23 at 05:02
  • @saurabhkamble See comment from 20 hours ago, https://stackoverflow.com/questions/76809392/php-date-issue-to-get-last-month-from-current-date?noredirect=1#comment135411547_76809392, or read one of the linked threads. – user3783243 Aug 02 '23 at 08:32

0 Answers0