【问题标题】:How to get Dates of Previous or Next Months in PHP?如何在 PHP 中获取上个月或下个月的日期?
【发布时间】:2013-07-11 08:58:52
【问题描述】:

我知道 date("Y")、date("m") 和 date("d") 将分别返回当前年份 (2013)、月份 (07) 和日期 (11)。

我正在使用日期格式:“2013-07-11”。我有这样的当前日期。现在我想使用 PHP 以某种方式获取值“2013-06-11”和“2013-08-11”。

获取此值的代码可能是什么(上个月的同一日期和下个月的同一日期)?

我试过了:

$LastMonth = date ("m") - 1;
$LastDate = date("Y") . "-0" . $LastMonth . "-" . date("d");

但这会在 10 月返回错误。 10 月将显示“2013-010-11”。

有什么更好的解决方案?谁能帮帮我?

【问题讨论】:

  • 您好,为了以后的参考,请始终记得先做一个快速的谷歌。搜索问题的标题会得到完美的答案,例如this one. 谢谢!
  • 二月和四月的2013-03-31 想要什么?

标签: php function date get


【解决方案1】:

与 PHP 的 strtotime() 一起使用:

echo date('Y-m-d', strtotime('+1 month')); //outputs 2013-08-11
echo date('Y-m-d', strtotime('-1 month')); //outputs 2013-06-11

【讨论】:

  • @Nirjhor:如果您觉得有帮助,请随时接受这个答案。 :-)
【解决方案2】:
$date = new DateTime( "2013-07-11");
$date->modify("+1 month");
echo $date->format(‘l, F jS, Y’);

【讨论】:

    【解决方案3】:

    试试这个

    $lst_month=mktime(0,0,0,date('m')-1,date('d'),date('Y'));
    echo "M<br>". date("Y-m-d",$lst_month);
    $next_month=mktime(0,0,0,date('m')+1,date('d'),date('Y'));
    echo "M<br>". date("Y-m-d",$next_month);
    

    【讨论】:

      【解决方案4】:
      $nextmonth=date("dmy",strtotime("+1 month"));
      $lastmonth=date("dmy",strtotime("-1 month"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多