如何在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。
当前回答
T返回给定日期当月的天数(date参见文档):
$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
其他回答
2行代码,你就完成了:
$oDate = new DateTime("2019-11-23");
// now your date object has been updated with last day of month
$oDate->setDate($oDate->format("Y"),$oDate->format("m"),$oDate->format("t"));
// or to just echo you can skip the above line using this
echo $oDate->format("Y-m-t");
我在这里将它包装在我的日期时间助手类中 https://github.com/normandqq/Date-Time-Helper 使用 $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
完成了
T返回给定日期当月的天数(date参见文档):
$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
$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;
}
}
在测试了许多解决方案之后,这个方法最适合我。
你可以为下个月的第一天创建一个日期,然后使用strtotime("-1 day", $firstOfNextMonth)