如何在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。
当前回答
有很多方法可以得到一个月的最后一天。
//to get last day of current month
echo date("t", strtotime('now'));
//to get last day from specific date
$date = "2014-07-24";
echo date("t", strtotime($date));
//to get last day from specific date by calendar
$date = "2014-07-24";
$dateArr=explode('-',$date);
echo cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]);
其他回答
你可以为下个月的第一天创建一个日期,然后使用strtotime("-1 day", $firstOfNextMonth)
你可以用几种方法找到这个月的最后一天。但是,您可以简单地使用PHP strtotime()和date()函数来实现这一点。我认为你的最终代码应该是这样的:
$a_date = "2009-11-23";
echo date('Y-m-t',strtotime($a_date));
现场演示
但是如果你正在使用PHP >= 5.2,我强烈建议你使用新的DateTime对象。例如:
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
现场演示
此外,你可以使用自己的函数来解决这个问题,如下所示:
/**
* Last date of a month of a year
*
* @param[in] $date - Integer. Default = Current Month
*
* @return Last date of the month and year in yyyy-mm-dd format
*/
function last_day_of_the_month($date = '')
{
$month = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$result = strtotime("{$year}-{$month}-01");
$result = strtotime('-1 second', strtotime('+1 month', $result));
return date('Y-m-d', $result);
}
$a_date = "2009-11-23";
echo last_day_of_the_month($a_date);
如果你知道一个月的最后一天,
public function getLastDateOfMonth($month)
{
$date = date('Y').'-'.$month.'-01'; //make date of month
return date('t', strtotime($date));
}
$this->getLastDateOfMonth(01); //31
我知道这有点晚了,但我认为有一种更优雅的方式来使用PHP 5.3+使用DateTime类:
$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
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");