在 PHP 中抓取特定月份的第一个日期和最后一个日期


Grabbing specific months first date and lastdate in PHP

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保存我想从中获取第一个日期和最后一个日期的月份编号。

例如,如果我做第一个月(1(,我希望它返回2012-01-01和

最后一个月(1(,它应该返回2012-01-31

我该怎么做?

试试这个:

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

试试这个,如果你使用的是 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');

等等..