如何在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。
其他回答
对我来说,最优雅的是使用DateTime
我不知道我没有看到DateTime::createFromFormat,一行程序
$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
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
我需要下个月的最后一天,也许有人会需要它:
echo date("Y-m-t", strtotime("next month")); //is 2020-08-13, return 2020-09-30
我在这里将它包装在我的日期时间助手类中 https://github.com/normandqq/Date-Time-Helper 使用 $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
完成了
你可以为下个月的第一天创建一个日期,然后使用strtotime("-1 day", $firstOfNextMonth)