6

I need help getting the previous months full date range in the following format: Y-m-d

I have successfully been able to get "this" months full date range but not the "previous" months full date range.

Any help is greatly appreciated!

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
three3
  • 2,756
  • 14
  • 57
  • 85

4 Answers4

14

This gets the job done correctly:

echo date('Y-m-01 - Y-m-t', strtotime('previous month'));

Here is the proof: http://ideone.com/L82ZW

Tadeck
  • 132,510
  • 28
  • 152
  • 198
8
    $last_month_first_day=strtotime('first day of last month');
    $no_of_days=date('t',$last_month_first_day);
    $date_value=$last_month_first_day;
    for($i=0;$i<$no_of_days;$i++)
    {
        echo date('Y-m-d',$date_value)."<br>";
        $date_value=strtotime("+1 day",$date_value);
    }

This code will print what you want..

First Date:

echo date('Y-m-d',strtotime('first day of last month'));

Last date:

echo date('Y-m-d',strtotime('last day of last month'));
Rajat Singhal
  • 11,234
  • 5
  • 38
  • 56
  • This works for me but it is printing out each date of the month. Is there a way to have it just show the "first" and "last day" instead of all of the dates in between. Example: '2011-12-01' & '2011-12-31'? – three3 Jan 01 '12 at 19:41
  • Check now ...Just First and Last date in most easy way to achieve..:) – Rajat Singhal Jan 01 '12 at 19:45
2

You could do something like this:

$month = 2;
$lastday = mktime(0, 0, 0, $month+1, 0, 2012);
$firstday = mktime(0, 0, 0, $month, 1, 2012);

$end = date("Y-m-d", $lastday);
$start = date("Y-m-d", $firstday);

The last day of any given month can be expressed as the "0" day of the next month.
http://www.php.net/manual/en/function.mktime.php

Audun Larsen
  • 958
  • 5
  • 7
0
// works with PHP 5.3 or later
$today = new DateTime();
$thisMonthFirstDay = $today->setDate($today->format('Y'), $today->format('m'), 1);
$previousMonthLastDay = $thisMonthFirstDay->sub(new DateInterval('P1D')); // substract 1 day

$daysInLastMonth = $previousMonthLastDay->format('d');

for($i=1; $i<=$daysInLastMonth; $i++) {
    $num = ($i < 10) ?'0'.$i :$i; // add zero in front if < 10
    echo $previousMonthLastDay->format('Y-m-') . $num. "\n";
} 
Master Drools
  • 728
  • 6
  • 18
  • This works for me but it is printing out each date of the month. Is there a way to have it just show the "first" and "last day" instead of all of the dates in between. Example: '2011-12-01' & '2011-12-31'? – three3 Jan 01 '12 at 19:41
  • Yes there is a way to do that. – Master Drools Feb 03 '12 at 12:03