Site icon WDB24

How to get the First and Last Day of every month in a given Year Using PHP

php featured image

In my recent project there was a requirement to display first day and last day of every month in a given year. So I had written a tiny but useful function in PHP to get array of month in a given year with their first and last day.

In the above function I am using some PHP built-in date and time functions. Following they are with their description.

mktime(hour,minute,second,month,day,year): is used to find the day for that date and return it in Unix timestamp. This function takes 6 parameters.

date(format,timestamp): is used to format a date and/or a time.

strtotime(time,now): Convert text datetimes into Unix timestamps

Timestamp: is a current time of an event recorded by computer.

Above function takes numeric year (2016) as parameter. Then there is a for loop running 12 times (because there are 12 months in a year). $getMonthTimeStamp converts $m (month) into timestamp. Where $currentYear is a given year. $month converts month’s timestamp into month name. $monthAndYear takes $month and $currentYear as a date and convert them in a UNIX timestamp. $currentYearArray[$month][‘MonthStartDate’] and $currentYearArray[$month][‘MonthEndDate’] is an array key which hold first day and last day of months. Once loop runs 12 time it returns an array $currentYearArray holding first and last day every month.

Exit mobile version