如何在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。
当前回答
这是一个完整的函数:
public function get_number_of_days_in_month($month, $year) {
// Using first day of the month, it doesn't really matter
$date = $year."-".$month."-1";
return date("t", strtotime($date));
}
这将输出如下:
echo get_number_of_days_in_month(2,2014);
输出:28
其他回答
function first_last_day($string, $first_last, $format) {
$result = strtotime($string);
$year = date('Y',$result);
$month = date('m',$result);
$result = strtotime("{$year}-{$month}-01");
if ($first_last == 'last'){$result = strtotime('-1 second', strtotime('+1 month', $result)); }
if ($format == 'unix'){return $result; }
if ($format == 'standard'){return date('Y-m-d', $result); }
}
http://zkinformer.com/?p=134
如果你使用碳API扩展PHP DateTime,你可以得到一个月的最后一天:
$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time
如果你想回到几个月前,你也可以这样做。
$list = [
0, 1, 2, 3
];
$date = new \Datetime();
$dates = [];
foreach($list as $item)
{
$set = clone $date;
$set->modify("-$item month ");
$dates[] = $set->modify("last day of this month");
}
return $dates;
我知道这有点晚了,但我认为有一种更优雅的方式来使用PHP 5.3+使用DateTime类:
$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
你的解决方案在这里。
$lastday = date('t',strtotime('today'));