0

I want to get the start and end date of the previous calender month.

So, it's July 2012 now, I want the function to return 01 June 2012 as start and 30 June 2012 as the end.

This is my code:

$current_month = date("Y-m-01 00:00:00");
$start_month = strtotime(date("Y-m-d", strtotime($current_month) . " -1 month"));
$end_month = strtotime(date("Y-m-d", strtotime($current_month) . " -1 second"));
echo "Start Month: " . date('Y-m-d',$start_month) . "( " . $start_month . ")<br>";
echo "End Month: " . date('Y-m-d',$end_month) . "( " . $end_month . ")<br>";

But it echo's:

Start Month: 2012-07-01( 1341093600)
End Month: 2012-07-01( 1341093600)

Any idea what I'm doing wrong?

Bird87 ZA
  • 2,313
  • 8
  • 36
  • 69
  • Check this, it can help you http://stackoverflow.com/questions/9735604/the-best-way-to-get-the-first-and-last-day-of-last-month – Adi Jul 10 '12 at 06:46

5 Answers5

1

Answering whats wrong with the code you posted, you just needed to move your round bracket over a little bit and you had it. :)

<?php
$current_month = date("Y-m-01 00:00:00");
$start_month = strtotime(date("Y-m-d", strtotime($current_month . " -1 month")));
$end_month = strtotime(date("Y-m-d", strtotime($current_month . " -1 day")));
echo "Start Month: " . date('Y-m-d',$start_month) . "( " . $start_month . ")<br>";
echo "End Month: " . date('Y-m-d',$end_month) . "( " . $end_month . ")<br>";
?>
Joshua
  • 126
  • 6
0

Try this, (check the manual of strtotime)

$now = time();
$current_month = date("Y-m-01 00:00:00", $now);
$start_month = strtotime("-1 month", $now);
$end_month = strtotime("-1 second", $now);
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Try something like this:

echo date("Y-m-d", mktime(0,0,0,date('m')-1,1,date('y')));
echo date("Y-m-d", mktime(0,0,0,date('m'),0,date('y')));
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
periklis
  • 10,102
  • 6
  • 60
  • 68
0

Seems a little bit oversized, what you (and the other answers :X) tried. It's justs

echo date('Y-m-d', strtotime('first day of last month'));
echo date('Y-m-d', strtotime('last day of last month'));

For arbitrary months

// 3 months in the past
echo date('Y-m-d', strtotime('first day of -3 months'));
echo date('Y-m-d', strtotime('last day of -3 months'));

// 3 months in the future
echo date('Y-m-d', strtotime('first day of +3 months'));
echo date('Y-m-d', strtotime('last day of +3 months'));

Read more At the manual

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
0
echo $firstdate= "01/".date('m')."/".date('Y') ;
 $lastdateofmonth=date('t',date('m'));
 echo $lastdate=$lastdateofmonth."/".date('m')."/".date('Y') ;

or

$date='2012-06-05 12:00:00';

echo "End = ".date("Y-m-t",strtotime($date)); 
echo "start = ".date("Y-m-01",strtotime($date)); 
Vaishu
  • 2,333
  • 3
  • 23
  • 25