如何在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。
当前回答
碳API扩展PHP DateTime
Carbon::parse("2009-11-23")->lastOfMonth()->day;
or
Carbon::createFromDate(2009, 11, 23)->lastOfMonth()->day;
将返回
30
其他回答
有很多方法可以得到一个月的最后一天。
//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]);
这是一个完整的函数:
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
另一种使用mktime而不是date('t')的方法:
$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)
所以用这种方法,它会计算它是31 30还是29
T返回给定日期当月的天数(date参见文档):
$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
$date1 = $year.'-'.$month;
$d = date_create_from_format('Y-m',$date1);
$last_day = date_format($d, 't');