Thursday 8 January 2015

PHP - How to find the last day of the month from date?

<?php
//For finding month last date, modify as follows, 
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');  //O/P    2009-11-30
echo "<br>--------------------------------------------<br>";
//For finding next month last date, modify as follows, 
 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');   //O/P 2009-12-31
 
 echo "<br>--------------------------------------------<br>";
$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());

$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());

$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());

echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';

echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';

echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';
//O/P
/*--------------------------------------------
Sun, Jan 4th 2015
Sun, Jan 11th 2015
Thu, Jan 1st 2015
Sat, Jan 31st 2015
Thu, Jan 1st 2015
Thu, Dec 31st 2015 */
 
//Last day of every month in the current year
 
function lastDateOfMonth($Month, $Year=-1) {
    if ($Year < 0) $Year = 0+date("Y");
    $aMonth         = mktime(0, 0, 0, $Month, 1, $Year);
    $NumOfDay       = 0+date("t", $aMonth);
    $LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
    return $LastDayOfMonth;
}

for($Month = 1; $Month <= 12; $Month++)
    echo date("Y-n-j", lastDateOfMonth($Month))."\n";  
//for 2015
/*
2015-1-31
2015-2-28
2015-3-31
2015-4-30
2015-5-31
2015-6-30
2015-7-31
2015-8-31
2015-9-30
2015-10-31
2015-11-30
2015-12-31 
*/ 

?>

0 comments:

Post a Comment