tags:

views:

590

answers:

7

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?

+1  A: 

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");
Biri
+1  A: 

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";
?>
Niyaz
+6  A: 
$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.

Michał Rudnicki
+1  A: 

I feel kind of stupid for asking for the first day of a month....:\

Thomas Owens
+1  A: 

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
ZombieSheep
A: 

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.

Pat
A: 

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));
Thomas Owens