views:

258

answers:

3

Whether anyway to find first date and last date in a month. Suppose have the date today as 21-04-2010, i want to find the first and last date of this month in php. I did this in mysql, but i need in php. Any one can help, Thanks in advance.

+3  A: 

This will give you the last day of the month:

function lastday($month = '', $year = '') {
   if (empty($month)) {
      $month = date('m');
   }
   if (empty($year)) {
      $year = date('Y');
   }
   $result = strtotime("{$year}-{$month}-01");
   $result = strtotime('-1 second', strtotime('+1 month', $result));
   return date('Y-m-d', $result);
}

And the first Day:

function firstDay($month = '', $year = '')
{
    if (empty($month)) {
      $month = date('m');
   }
   if (empty($year)) {
      $year = date('Y');
   }
   $result = strtotime("{$year}-{$month}-01");
   return date('Y-m-d', $result);
} 
Luis
+3  A: 

You can use the date function to find how many days in a month there are.

// Get the timestamp for the date/month in question.
$ts = strtotime('April 2010');

echo date('t', $ts); 
// Result: 30, therefore, April 30, 2010 is the last day of that month.

Hope that helps.

EDIT: After reading Luis' answer, it occurred to me you may want it in the right format (YY-mm-dd). It may be obvious, but doesn't hurt to mention:

// After the above code
echo date('Y-m-t', $ts); 
hlissner
+3  A: 

This will give you the first and last second of the current month. The parts of the date that you don't specify are filled in using the strtotime() value, so 'm' gives you the month from that timestamp, and 't' gives you the last day of the month from that time stamp.

echo date('m-01-Y 00:00:00',strtotime('this month')) . '<br/>';
echo date('m-t-Y 12:59:59',strtotime('this month')) . '<br/>';

See http://php.net/manual/en/function.date.php for details.

Nathan Long
It's all the way at the bottom, but actually the best answer of them all.
Evert
Simple answer and super also...
Karthik