How to find the last day of the month from date?

How can I get the last day of the month in PHP?

Given:

$a_date = "2009-11-23"

I want 2009-11-30; and given

$a_date = "2009-12-23"

I want 2009-12-31.


t返回天在一个特定的日期(请参阅文档月份的数字date ):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));

The code using strtotime() will fail after year 2038. (as given in the first answer in this thread) For example try using the following:

$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));

It will give answer as: 1970-01-31

So instead of strtotime, DateTime function should be used. Following code will work without Year 2038 problem:

$d = new DateTime( '2040-11-23' ); 
echo $d->format( 'Y-m-t' );

我知道这有点晚,但我认为使用DateTime类在PHP 5.3+中做到这一点更加优雅:

$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
链接地址: http://www.djcxy.com/p/57290.html

上一篇: 查找两个日期之间的天数

下一篇: 如何从日期查找月份的最后一天?