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';
You might want to look at the strtotime
and date
functions.
<?php
$query_date = '2010-02-04';
// First day of the month.
echo date('Y-m-01', strtotime($query_date));
// Last day of the month.
echo date('Y-m-t', strtotime($query_date));
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"));
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..