Monday 24 September 2018

Php function to get the last day of a month

Here is a function that would get the last day of a given month as a date in format Y-m-d. It first adds 1 month to the 1st date of the given month, then subtracts 1 second from the resulting date which brings back to the last date of the given month.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
    Last date of a month of a year
     
    @param[in] $month - Integer. Default = Current Month
    @param[in] $year - Integer. Default = Current Year
     
    @return Last date of the month and year in yyyy-mm-dd format
*/
function last_day($month = '', $year = '')
{
   if (empty($month))
   {
      $month = date('m');
   }
    
   if (empty($year))
   {
      $year = date('Y');
   }
    
   $result = strtotime("{$year}-{$month}-01");
   $result = strtotime('-1 second', strtotime('+1 month', $result));
 
   return date('Y-m-d', $result);
}

0 comments:

Post a Comment