Asked  7 Months ago    Answers:  5   Viewed   38 times

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


$a_date = "2009-11-23"

I want 2009-11-30; and given

$a_date = "2009-12-23"

I want 2009-12-31.



t returns the number of days in the month of a given date (see the docs for date):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
Wednesday, March 31, 2021
answered 7 Months ago

You could also take a look at the DatePeriod class:

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')

Which should get you an array with DateTime objects.

To iterate

foreach ($period as $key => $value) {
Wednesday, March 31, 2021
answered 7 Months ago

calendar.monthrange provides this information:

calendar.monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

>>> import calendar
>>> calendar.monthrange(2002, 1)
(1, 31)
>>> calendar.monthrange(2008, 2)  # leap years are handled correctly
(4, 29)
>>> calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren't leap years
(0, 28)


calendar.monthrange(year, month)[1]

seems like the simplest way to go.

Tuesday, June 1, 2021
answered 5 Months ago

You need to call DateInterval::format() to display that difference as a string.

echo $diff->format('%d days');

See the manual for all of the available formatting options.

Wednesday, July 7, 2021
answered 4 Months ago

How about using DaysInMonth:

DateTime createDate = new DateTime (year, month,
                                    DateTime.DaysInMonth(year, month));

(Note to self - must make this easy in Noda Time...)

Monday, September 13, 2021
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :