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_dat
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 :
$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
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));
Your solution is here..
$lastday = date('t',strtotime('today'));
function first_last_day($string, $first_last, $format) {
$result = strtotime($string);
$year = date('Y',$result);
$month = date('m',$result);
$result = strtotime("{$year}-{$month}-01");
if ($first_last == 'last'){$result = strtotime('-1 second', strtotime('+1 month', $result)); }
if ($format == 'unix'){return $result; }
if ($format == 'standard'){return date('Y-m-d', $result); }
}
http://zkinformer.com/?p=134
An other way using mktime and not date('t') :
$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)
So this way it calculates either if it is 31,30 or 29
The code using strtotime() will fail after year 2038. (as given in the first answer in this thread) For example try using the following:
$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));
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:
$d = new DateTime( '2040-11-23' );
echo $d->format( 'Y-m-t' );