【问题标题】:Get first and last day from last month [duplicate]获取上个月的第一天和最后一天[重复]
【发布时间】:2013-11-25 00:12:14
【问题描述】:

我有这个:

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

还有其他方法吗?

谢谢

【问题讨论】:

  • 完全不清楚你想要什么。
  • @wumm OP 想要上个月的第一天和最后一天,而不是当月的。
  • @Marcell Fülöp:不清楚。哈哈。试着再读一遍。别人给我的建议,你是唯一不理解的人。
  • -1 请先使用SO站点搜索,至少有两个相同的重复...

标签: php date


【解决方案1】:

下面的代码应该可以工作

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

【讨论】:

  • 谢谢。我会测试它。
  • 输出(2013-10-012013-10-31)将在 $startOutput$endOutput 变量中。
  • 我已经为 $startOutput: 2168-09-10...
  • 糟糕,参数的顺序错误!它现在应该可以工作了! :)
【解决方案2】:

只需使用 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

【讨论】:

    【解决方案3】:

    这是一个方便的小功能,可以满足您的需求。您将返回一个数组,其中包含上个月的第一天和最后一天到提供的日期:-

    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)
    

    See it working.

    【讨论】:

    • 谢谢,但为什么要白白费力呢? date("Y-m-d", mktime(0, 0, 0, date("m")+1, 1, date("Y"))) 完成了这项工作。
    • 是的,但 mktime 不允许闰年和 DST 更改。这将。
    • 你确定 mktime 不会那样工作吗?
    • 是的,可以肯定的是,尽管我总是准备被证明是错误的。
    • @user2984349 查看我的编辑。
    猜你喜欢
    • 2015-04-03
    • 1970-01-01
    • 2014-03-22
    • 2017-01-07
    • 2013-02-15
    • 2017-01-09
    • 2019-03-04
    • 2016-06-12
    • 1970-01-01
    相关资源
    最近更新 更多