获取前几个月的最后几天

时间:2011-11-17 16:36:25

标签: php arrays

for($i=0; $i<4; $i++)
{

 $monthArr[] = date("Y-m-d H:i:s", strtotime('2011-10-31'. -1*$i.' month'));

 }

结果:

Array
(
    [0] => 2011-10-31
    [1] => 2011-10-01    //Here should be 2011-09-30
    [2] => 2011-08-31
    [3] => 2011-07-31
)

我希望输出如下,谢谢!

Array
(
    [0] => 2011-10-31
    [1] => 2011-09-30
    [2] => 2011-08-31
    [3] => 2011-07-31
)

7 个答案:

答案 0 :(得分:6)

strtotime('2011-10-31 -1 month');

这相当于2011-09-31,它不存在,因此会改为2011-09-30之后的第二天,即2011-10-01。

不要循环遍历该月的最后一天(可变),而是尝试循环该月的第一天,然后计算该月的最后一天,即

date( 'Y-m-t', strtotime('2011-10-01 '. -1*$i .' month') );

编辑:date()函数的“t”标志返回该月的最后一天。

答案 1 :(得分:2)

for($i=0; $i<4; $i++) {
    $monthArr[] = date("Y-m-d H:i:s", strtotime('last day of 2011-10-31 '. -1*$i.' month'));
}

而不是'2011-10-31',您也可以在当月写“今天”。

示例输出:

array(10) {
  [0]=>
  string(19) "2011-10-31 00:00:00"
  [1]=>
  string(19) "2011-09-30 00:00:00"
  [2]=>
  string(19) "2011-08-31 00:00:00"
  [3]=>
  string(19) "2011-07-31 00:00:00"
  [4]=>
  string(19) "2011-06-30 00:00:00"
  [5]=>
  string(19) "2011-05-31 00:00:00"
  [6]=>
  string(19) "2011-04-30 00:00:00"
  [7]=>
  string(19) "2011-03-31 00:00:00"
  [8]=>
  string(19) "2011-02-28 00:00:00"
  [9]=>
  string(19) "2011-01-31 00:00:00"
}

答案 2 :(得分:1)

$days_past = 0;    
for($i=0; $i<4; $i++) {
    $monthArr[] = date("Y-m-d H:i:s", strtotime('2011-10-31 '.$days_past.' days'));
    $days_past -= cal_days_in_month(CAL_GREGORIAN, 10 - $i, 2011);
}
  • 0天
  • 31天
  • 61天 等

答案 3 :(得分:1)

PHP有DateTime类可用,而不是datestrtotime函数,因为你可以暗示使用什么时区,因此当它到来时你可以“安全” DST和许多其他事情。

如何使用它来解决您的问题:

$date = '2011-11-30'; // our date that we deal with 

$tz = new DateTimeZone('Europe/London');

// create new DateTime object specifying the format and the date we create from as well as the time zone we're in
$dt = DateTime::createFromFormat('Y-m-d', $date, $tz);

// let's substract 1 month from current DateTime object     
$sub = $dt->sub(new DateInterval('P1M')); // P stands for PERIOD, 1 stands for ONE and M stands for MONTH - so it means we're substracting period of 1 month 

// output the new date 

echo $sub->format('Y-m-d);

答案 4 :(得分:0)

我想你想要mktime()函数:

http://us2.php.net/mktime

// I'm assuming today's date here, but adjust accordingly
$start_day   = date('j');
$start_month = date('n');
$start_year  = date('Y');
for($i=0; $i<4; $i++)
{
    $monthArr[] = date("Y-m-d H:i:s", mktime(1, 1, 1, $start_day, $start_month - $i, $start_year));
}

答案 5 :(得分:0)

这有帮助:

for($i = 0, $j=11; $i < 4; $i++) {

    echo date("Y-m-d", strtotime("-1 day", strtotime(date("Y-$j-01"))));
    echo "<br />";
    $j--;
}

答案 6 :(得分:0)

我也喜欢PHP DateTime类。 使用它时,每件事都变得简单易行。

// Get last day of previous month
$date = new DateTime();
$dayOfMonth = $date->format('j');
$date->sub(new DateInterval('P' . $dayOfMonth . 'D'));
echo $date->format('Y-m-d');

如果你只是想要获得一个月的最后一次,为什么不只是简单地使用一个数组,因为只有2月需要护理,其他月份有固定的最后一天。

如果您想获得一周的开始日期和结束日期,则可能需要DateTime。