Timestamps of start and end of month

With PHP 5.3, you can do

$oFirst = new DateTime('first day of this month');
$oLast  = new DateTime('last day of this month');
$oLast->setTime(23, 59, 59);

In PHP 5.2

Note: as AllThecode pointed out in the comments below, this next example only works if you do the $oFirst portion first. If you add +1 month to new DateTime the result will jump an extra month ahead on the last day of the month (as of php 5.5.9).

$oToday = new DateTime();
$iTime  = mktime(0, 0, 0, $oToday->format('m'), 1, $oToday->format('Y'));
$oFirst = new DateTime(date('r', $iTime));

$oLast  = clone $oFirst;
$oLast->modify('+1 month');
$oLast->modify('-1 day');
$oLast->setTime(23, 59, 59);

You can use mktime and date:

$first_minute = mktime(0, 0, 0, date("n"), 1);
$last_minute = mktime(23, 59, 59, date("n"), date("t"));

That is for the current month. If you want to have it for any month, you have change the month and day parameter accordingly.

If you want to generate it for every month, you can just loop:

$times  = array();
for($month = 1; $month <= 12; $month++) {
    $first_minute = mktime(0, 0, 0, $month, 1);
    $last_minute = mktime(23, 59, 59, $month, date('t', $first_minute));
    $times[$month] = array($first_minute, $last_minute);
}

DEMO


Use mktime for generating timestamps from hour/month/day/... values and cal_days_in_month to get the number of days in a month:

$month = 1; $year = 2011;
$firstMinute = mktime(0, 0, 0, $month, 1, $year);
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$lastMinute = mktime(23, 59, 0, $month, $days, $year);

Tags:

Php