I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?
The easiest way to do this with PHP is
$dateBegin = strtotime("first day of last month");
$dateEnd = strtotime("last day of last month");
echo date("MYDATEFORMAT", $dateBegin);
echo "<br>";
echo date("MYDATEFORMAT", $dateEnd);
Or the last week
if (date('N', time()) == 7) {
$dateBegin = strtotime("-2 weeks Monday");
$dateEnd = strtotime("last Sunday");
} else {
$dateBegin = strtotime("Monday last week");
$dateEnd = strtotime("Sunday last week");
}
Or the last year
$dateBegin = strtotime("1/1 last year");
$dateEnd = strtotime("12/31 this year");
$first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));
$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));
See date() in PHP documentation.
From here(get next month last day) that is marked as duplicated, so i can't add comment there, but people can got bad answers from there.
Correct one for last day of next month:
echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-t'));
Correct one for first day of next month:
echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-01'));
Code like this will be providing March from January, so that's not what could be expected.
echo ((new DateTime())->modify('+1 month')->format('Y-m-t'));
Example; I want to get first day and last day of current month.
$month = (int) date('F');
$year = (int) date('Y');
date('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year)); //first
date('Y-m-d', mktime(0, 0, 0, $month + 2, 0, $year)); //last
When you run this for instance at date 2015-01-09, the first and last values will be sequentially;
2015-01-01
2015-01-31
Tested.
By the way @ZombieSheep solution
date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY));
does not work it should be
date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
Of course @Michał Słaby's accepted solution is the simplest.
The first day of the month is always 1. So it will become
YYYY-MM-01
the last day can be calculated as:
<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>