-2

I have this:

$today=date('Y-m-d');
// echo "2013-11-12";

I want to get the last month range like this:

$startLastMonth = "2013-10-01";
$endLastMonth   = "2013-10-31";

I try that but it's does not meet my desire as I need to put 42:

$startLastMonth = mktime(0, 0, 0, date("Y"), date("m"),   date("d")-42);

Is there another way ?

Thanks

user2984349
  • 21
  • 1
  • 2

3 Answers3

4

The code below should work

$startLastMonth = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));
$endLastMonth = mktime(0, 0, 0, date("m"), 0, date("Y"));

What you're doing is telling PHP that a) you want the 1st day of the previous month (date("m") - 1), and b) telling PHP you want the 0th day of the current month, which, according to mktime documentation, becomes the last day of the previous month. Documentation can be found here: http://php.net/manual/en/function.mktime.php

If you want to format the output as in your you can do

$startOutput = date("Y-m-d", $startLastMonth);
$endOutput = date("Y-m-d", $endLastMonth);
Alexander Kuzmin
  • 1,120
  • 8
  • 16
3

Just use the relative date/time formats that are provided by PHP:

var_dump( new DateTime( 'first day of last month' ) );
var_dump( new DateTime( 'last day of last month' ) );

See: http://www.php.net/manual/en/datetime.formats.relative.php

feeela
  • 29,399
  • 7
  • 59
  • 71
0

Here's a handy little function that will do what you want. You will get back an array containing the first and last days of the previous month to the date supplied:-

function getLastMonth(DateTime $date)
{
    //avoid side affects
    $date = clone $date;
    $date->modify('first day of last month');
    return array(
        $date->format('Y-m-d'),
        $date->format('Y-m-t'),
    );
}

var_dump(getLastMonth(new \DateTime()));

Output:-

array (size=2)
  0 => string '2013-10-01' (length=10)
  1 => string '2013-10-31' (length=10)

In PHP > 5.3 you can do this:-

list($start, $end) = getLastMonth(new \DateTime());
var_dump($start, $end);

Output:-

string '2013-10-01' (length=10)
string '2013-10-31' (length=10)

See it working.

vascowhite
  • 18,120
  • 9
  • 61
  • 77