0

Currently I'm using <?php echo date('F', strtotime('-1 month')); ?>, which has been working fine but today it the 31st of July, but there are only 30 days in June.

For some reason echo date('F', strtotime('-1 month')) and echo date('F') return the same month e.g. July. Then echo date('F', strtotime('-2 month')) and echo date('F', strtotime('-3 month')) return May and so on.

GRS
  • 2,807
  • 4
  • 34
  • 72
  • 7
    We get these questions at the end of every month – John Conde Jul 31 '17 at 17:13
  • 1
    Can't understand why people spend more time writing the answer instead of looking on Google : https://stackoverflow.com/questions/1889758/getting-last-months-date-in-php – Vincent Decaux Jul 31 '17 at 17:15
  • 1
    Possible duplicate of [how can i get previous month name in php](https://stackoverflow.com/questions/13933825/how-can-i-get-previous-month-name-in-php) – GrumpyCrouton Jul 31 '17 at 17:15
  • Be careful of the "- 1 month" construct. It makes sense some of the time and other times it does not. The meaning of "month" is ambiguous - some have more days than others. You will get good results if you normalize today's date to the first day of the current month, then subtract one day. – Ray Paseur Jul 31 '17 at 17:22

2 Answers2

1

Check this. This will give you previous Month Name

<?php

  $pp = date('m', strtotime(date('Y-m')." -1 month"));
  echo date('F', mktime(0, 0, 0, $pp, 10));
?>
Harpreet Singh
  • 999
  • 9
  • 19
  • Perfect, thanks. Other solutions, even linked in the thread don't give a solution for an arbitrary month. This has month or month name which is perfect. – GRS Jul 31 '17 at 17:25
  • Sorry, I had to wait 10 mins – GRS Aug 01 '17 at 00:35
1

This should work no matter how many days there are in the month.

<?php // demo/temp_grs.php
/**
 * Previous Month
 *
 * https://stackoverflow.com/questions/45421749/php-echo-the-name-of-the-previous-month-e-g-june
 */
error_reporting(E_ALL);
echo '<pre>';


$start = date('Y-m-1') . '- 1 day';
$month = date('F', strtotime($start));
echo $month;
Ray Paseur
  • 2,106
  • 2
  • 13
  • 18