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?
Just to verify that I didn't miss any loose ends:
$startDay = 1;
if (date("m") == 1) {
$startMonth = 12;
$startYear = date("Y") - 1;
$endMonth = 12;
$endYear = date("Y") - 1;
}
else {
$startMonth = date("m") - 1;
$startYear = date("Y");
$endMonth = date("m") - 1;
$endYear = date("Y");
}
$endDay = date("d") - 1;
$startDate = date('Y-m-d', mktime(0, 0, 0, $startMonth , $startDay, $startYear));
$endDate = date('Y-m-d', mktime(0, 0, 0, $endMonth, $endDay, $endYear));
<?php
echo "Month Start - " . $monthStart = date("Y-m-1") . "<br/>";
$num = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y"));
echo "Monthe End - " . $monthEnd = date("Y-m-".$num);
?>
OK, first is dead easy.
date ('Y-m-d', mktime(0,0,0,MM,01,YYYY));
Last is a little trickier, but not much.
date ('Y-m-d', mktime(0,0,0,MM + 1,-1,YYYY));
If I remember my PHP date stuff correctly...
**edit - Gah! Beaten to it about a million times...
Edit by Pat:
Last day should have been
date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
First day is always YYYY-MM-01, isn't it? Example: date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008))
Last day is the previous day of the next month's first day:
$date = new DateTime("2008-09-01");
$date->modify("-1 day");
echo $date->format("Y-m-d");
try this to get the number of days in the month:
$numdays = date('t', mktime(0, 0, 0, $m, 1, $Y));