[php] how to get the first and last days of a given month

I wish to rewrite a mysql query which use month() and year() functions to display all the posts from a certain month which goes to my function as a 'Y-m-d' parameter format, but I don't know how can I get the last day of the given month date.

$query_date = '2010-02-04';
list($y, $m, $d) = explode('-', $query_date);
$first_day = $y . '-' . $m . '-01';

This question is related to php date

The answer is


cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.


Print only current month week:

function my_week_range($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
    $start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
    if($currentWeek==1)
        {$start_date = date('Y-m-01', strtotime($date));}
    else if($currentWeek==5)
       {$end_date = date('Y-m-t', strtotime($date));}
    else
       {}
    return array($start_date, $end_date );
}

$date_range=list($start_date, $end_date) = my_week_range($new_fdate);

I know this question has a good answer with 't', but thought I would add another solution.

$first = date("Y-m-d", strtotime("first day of this month"));
$last = date("Y-m-d", strtotime("last day of this month"));

Basically:

$lastDate = date("Y-m-t", strtotime($query_d));

Date t parameter return days number in current month.


Try this , if you are using PHP 5.3+, in php

$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');

For finding next month last date, modify as follows,

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');

and so on..


$month = 10; // october

$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');

## Get Current Month's First Date And Last Date

echo "Today Date: ". $query_date = date('d-m-Y');
echo "<br> First day of the month: ". date('01-m-Y', strtotime($query_date));
echo "<br> Last day of the month: ". date('t-m-Y', strtotime($query_date));

// First date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));
echo '<br />';
// Last date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m')+1, 0, date('Y')));