【问题标题】:Grabbing specific months first date and lastdate in PHP在 PHP 中获取特定月份的第一个日期和最后一个日期
【发布时间】:2012-02-10 09:39:30
【问题描述】:
function firstOfMonth() {
return date("m/d/Y", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
}

function lastOfMonth() {
return date("m/d/Y", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
}

是我必须得到当月的第一天日期和最后一天日期。

现在我想稍微改变一下,所以在这两个函数中它们都有一个带有 $month 的参数,其中 $month 包含我想从中获取第一个日期和最后一个日期的月份的编号。

例如,如果我执行 firstOfMonth(1),我希望它返回 2012-01-01,而 lastOfMonth(1) 它应该返回 2012-01-31

我该怎么做?

【问题讨论】:

标签: php


【解决方案1】:

试试这个:

$date = new DateTime('2012-02-01');

// first day
echo $date->format('d-m-Y');

// t = days in month, minutes one to go to the last.
$date->modify(sprintf('+%d day', $date->format('t')-1));

// Last day
echo $date->format('d-m-Y');

【讨论】:

    【解决方案2】:

    试试这个,如果你使用的是 PHP 5.3+,

    $query_date = '2012-01-01';
    $date = new DateTime($query_date);
    //First day of month
    $date->modify('first day of this month');
    $firstday= $date->format('Y-m-d');
    //Last day of month
    $date->modify('last day of this month');
    $lastday= $date->format('Y-m-d');
    

    查找下个月的最后一个日期,修改如下,

    $date->modify('last day of 1 month');
    echo $date->format('Y-m-d');
    

    等等..

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 2021-12-07
      • 1970-01-01
      • 2014-06-26
      • 2013-01-06
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 2016-10-10
      相关资源
      最近更新 更多