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.
Here is a complete function:
This would output following:
Output: 28
The code using strtotime() will fail after year 2038. (as given in the first answer in this thread) For example try using the following:
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:
If you use the Carbon API extension for PHP DateTime, you can get the last day of the month with:
You can find last day of the month several ways. But simply you can do this using PHP strtotime() and date() function.I'd imagine your final code would look something like this:
Live Demo
But If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:
Live Demo
Also, you can solve this using your own function like below:
I know this is a little bit late but i think there is a more elegant way of doing this with
PHP 5.3+
by using the DateTime class :You can also use it with datetime