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.
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.
You could create a date for the first of the next month, and then use
strtotime("-1 day", $firstOfNextMonth)
What is wrong - The most elegant for me is using
DateTime
I wonder I do not see
DateTime::createFromFormat
, one-linerI am late but there are a handful of easy ways to do this as mentioned:
Using mktime() is my go to for complete control over all aspects of time... I.E.
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.
This a much more elegant way to get the end of the month:
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