Asked  7 Months ago    Answers:  5   Viewed   38 times

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.

 Answers

66

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
 
binoculars
answered 7 Months ago
96

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) {
    //$value->format('Y-m-d')       
}
Wednesday, March 31, 2021
 
CAMason
answered 7 Months ago
69

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)

so:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

Tuesday, June 1, 2021
 
Taptronic
answered 5 Months ago
24

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
 
mattltm
answered 4 Months ago
65

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
 
newbStudent
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 :