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

2018-12-31 15:24发布

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.

标签: php date
23条回答
何处买醉
2楼-- · 2018-12-31 16:01

You could create a date for the first of the next month, and then use strtotime("-1 day", $firstOfNextMonth)

查看更多
几人难应
3楼-- · 2018-12-31 16:01

What is wrong - The most elegant for me is using DateTime

I wonder I do not see DateTime::createFromFormat, one-liner

$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
查看更多
与君花间醉酒
4楼-- · 2018-12-31 16:02

I am late but there are a handful of easy ways to do this as mentioned:

$days = date("t");
$days = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$days = date("j",mktime (date("H"),date("i"),date("s"),(date("n")+1),0,date("Y")));

Using mktime() is my go to for complete control over all aspects of time... I.E.

echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));

Setting the day to 0 and moving your month up 1 will give you the last day of the previous month. 0 and negative numbers have the similar affect in the different arguements. PHP: mktime - Manual

As a few have said strtotime isn't the most solid way to go and little if none are as easily versatile.

查看更多
梦该遗忘
5楼-- · 2018-12-31 16:02

This a much more elegant way to get the end of the month:

  $thedate = Date('m/d/Y'); 
  $lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate)))); 
查看更多
不再属于我。
6楼-- · 2018-12-31 16:03
$date1 = $year.'-'.$month; 
$d = date_create_from_format('Y-m',$date1); 
$last_day = date_format($d, 't');
查看更多
何处买醉
7楼-- · 2018-12-31 16:05

I have wrapped it in my date time helper class here https://github.com/normandqq/Date-Time-Helper using $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();

And it is done

查看更多
登录 后发表回答