如何在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。
当前回答
如果您使用的是32位系统,那么由于2038年问题,strtotime()代码将在2038年之后失败。
例如,在32位系统上,此代码将回显1970-01-31:
$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));
如果你需要你的代码支持32位系统,那么你应该使用DateTime函数:
$d = new DateTime('2040-11-23');
echo $d->format('Y-m-t');
该代码将在32位或64位系统上正确地输出2040-11-30。
其他回答
这是一个更优雅的表达月底的方式:
$thedate = Date('m/d/Y');
$lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate))));
另一种使用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
这应该可以工作:
$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/>';
如果你使用碳API扩展PHP DateTime,你可以得到一个月的最后一天:
$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time
$date1 = $year.'-'.$month;
$d = date_create_from_format('Y-m',$date1);
$last_day = date_format($d, 't');