如何在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。
当前回答
还有一个内置的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
其他回答
如果你使用碳API扩展PHP DateTime,你可以得到一个月的最后一天:
$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time
还有一个内置的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
这应该可以工作:
$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());
$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());
$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());
echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';
echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';
echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';
对我来说,最优雅的是使用DateTime
我不知道我没有看到DateTime::createFromFormat,一行程序
$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
$date1 = $year.'-'.$month;
$d = date_create_from_format('Y-m',$date1);
$last_day = date_format($d, 't');