Get the first and last day of the month in PHP

By: Binu v Pillai Printer Friendly Format    

Another useful function to find the first and last day of the month from the given date in PHP.

<?php

function findFirstAndLastDay($anyDate)
{
    //$anyDate           =    '2009-08-25';    // date format should be yyyy-mm-dd
    list($yr,$mn,$dt)    =    split('-',$anyDate);    // separate year, month and date
    $timeStamp           =    mktime(0,0,0,$mn,1,$yr);    //Create time stamp of the first day from the give date.
    $firstDay            =     date('D',$timeStamp);    //get first day of the given month
    list($y,$m,$t)       =     split('-',date('Y-m-t',$timeStamp)); //Find the last date of the month and separating it
    $lastDayTimeStamp    =    mktime(0,0,0,$m,$t,$y);//create time stamp of the last date of the give month
    $lastDay             =    date('D',$lastDayTimeStamp);// Find last day of the month
    $arrDay              =    array("$firstDay","$lastDay"); // return the result in an array format.
    
    return $arrDay;
}

//Usage
$dayArray=array();
$dayArray=findFirstAndLastDay('2009-02-25');
print $dayArray[0];
print $dayArray[1];
?>
eric dot schultz at NOSPAM dot CyVon dot com 17-Dec-2008 02:33
Here is another gmgetdate that is a little faster/suscint (no loops). 

<?php 
function gmgetdate2($ts = null){ 
        $k = array('seconds','minutes','hours','mday', 
                'wday','mon','year','yday','weekday','month',0); 
        return(array_combine($k,split(":", 
                gmdate('s:i:G:j:w:n:Y:z:l:F:U',is_null($ts)?time():$ts)))); 
        } 
?>  



Ask a Question



Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial