Get previous month date range
Pergunta
I need help getting the previous months full date range in the following format: Y-m-d
I have successfully been able to get "this" months full date range but not the "previous" months full date range.
Any help is greatly appreciated!
Solução
$last_month_first_day=strtotime('first day of last month');
$no_of_days=date('t',$last_month_first_day);
$date_value=$last_month_first_day;
for($i=0;$i<$no_of_days;$i++)
{
echo date('Y-m-d',$date_value)."<br>";
$date_value=strtotime("+1 day",$date_value);
}
This code will print what you want..
First Date:
echo date('Y-m-d',strtotime('first day of last month'));
Last date:
echo date('Y-m-d',strtotime('last day of last month'));
Outras dicas
This gets the job done correctly:
echo date('Y-m-01 - Y-m-t', strtotime('previous month'));
Here is the proof: http://ideone.com/L82ZW
You could do something like this:
$month = 2;
$lastday = mktime(0, 0, 0, $month+1, 0, 2012);
$firstday = mktime(0, 0, 0, $month, 1, 2012);
$end = date("Y-m-d", $lastday);
$start = date("Y-m-d", $firstday);
The last day of any given month can be expressed as the "0" day of the next month.
http://www.php.net/manual/en/function.mktime.php
// works with PHP 5.3 or later
$today = new DateTime();
$thisMonthFirstDay = $today->setDate($today->format('Y'), $today->format('m'), 1);
$previousMonthLastDay = $thisMonthFirstDay->sub(new DateInterval('P1D')); // substract 1 day
$daysInLastMonth = $previousMonthLastDay->format('d');
for($i=1; $i<=$daysInLastMonth; $i++) {
$num = ($i < 10) ?'0'.$i :$i; // add zero in front if < 10
echo $previousMonthLastDay->format('Y-m-') . $num. "\n";
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow