获取上个月的第一天和最后一天


Get first and last day from last month

>我有这个:

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

我想得到上个月的范围,如下所示:

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

尝试这样做,但它不符合我的愿望,因为我需要输入 42:

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

还有别的办法吗?

谢谢

下面的代码应该可以工作

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

你正在做的是告诉 PHP a) 你想要上个月的第一天(date("m") - 1 ),b) 告诉 PHP 你想要月的第 0 天,根据 mktime 文档,这变成了上个月的最后一天。文档可在此处找到:http://php.net/manual/en/function.mktime.php

如果您想像您的一样格式化输出,您可以这样做

$startOutput = date("Y-m-d", $startLastMonth);
$endOutput = date("Y-m-d", $endLastMonth);

只需使用 PHP 提供的相对日期/时间格式:

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

请参阅:http://www.php.net/manual/en/datetime.formats.relative.php

这是一个方便的小函数,可以做你想做的事。您将获得一个数组,其中包含上个月的第一天和最后几天到提供的日期:-

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()));

输出:-

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

在 PHP> 5.3 中,您可以这样做:

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

输出:-

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

看到它工作。