如何在PHP中获得每月的最后一天?
考虑到:
$a_date = "2009-11-23"
我想要2009-11-30;鉴于
$a_date = "2009-12-23"
我要2009-12-31。
如何在PHP中获得每月的最后一天?
考虑到:
$a_date = "2009-11-23"
我想要2009-11-30;鉴于
$a_date = "2009-12-23"
我要2009-12-31。
当前回答
我在这里将它包装在我的日期时间助手类中 https://github.com/normandqq/Date-Time-Helper 使用 $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
完成了
其他回答
还有一个内置的PHP函数cal_days_in_month()?
"此函数将返回指定日历的某月中的天数。" http://php.net/manual/en/function.cal-days-in-month。
echo cal_days_in_month(CAL_GREGORIAN, 11, 2009);
// = 30
$startDate = '2011-12-01';
$endDate = date('Y-m');
while (true) {
try {
$startDateTime = new DateTime($startDate);
$startDateTime->add(new DateInterval('P1M'));
$startDate = $startDateTime->format('Y-m-d');
$endTime = $startDateTime->format('Y-m-t');
echo $startDate . ' => ' . $endTime . PHP_EOL;
if ($startDateTime->format('Y-m') == $endDate) {
break;
}
} catch (Exception $exception) {
var_dump($exception->getMessage());
break;
}
}
在测试了许多解决方案之后,这个方法最适合我。
您也可以将它与datetime一起使用
$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');
如果你知道一个月的最后一天,
public function getLastDateOfMonth($month)
{
$date = date('Y').'-'.$month.'-01'; //make date of month
return date('t', strtotime($date));
}
$this->getLastDateOfMonth(01); //31
现在,如果你有月份和年份,DateTime可以很方便地做到这一点
$date = new DateTime('last day of '.$year.'-'.$month);
来自另一个DateTime对象
$date = new DateTime('last day of '.$otherdate->format('Y-m'));