下个月和上个月从给定日期php获得的最佳解决方案是什么


What is best solution to get next and previous month from given date php

我想从给定日期起得到下个月和上个月。这是我的密码。

$month='2011-01-20';

$prevMOnth=funP($month);$nextMonth=funN($month);

最好的解决方案是什么。

$next_month_ts = strtotime('2011-01-20 +1 month');
$prev_month_ts = strtotime('2011-01-20 -1 month');
$next_month = date('Y-m-d', $next_month_ts);
$prev_month = date('Y-m-d', $prev_month_ts);

前面提到的代码在31天(或3月)的月末可能不起作用:$prev_month_ts=strtotime('2011-01-20-1个月');

这是获取上月名称的最佳解决方案。获取本月第一天的日期,然后减去1天,然后获取月份名称:

date('F', strtotime('-1 day', strtotime(date('Y-m-01'))));

并且获取下个月的名称。获取本月最后一天的日期,然后添加1天,然后获取月份名称:

date('F', strtotime('+1 day', strtotime(date('Y-m-t'))));

不知道这是否是最好的方法,但它内置在php中,请查看strtotime

编辑:样本代码

$month = '2011-01-20';
$timestamp = strtotime ("+1 month",strtotime ($month));
$nextMonth  =  date("Y-m-d",$timestamp);
$date = "2012-01-25";
$priormonth = date ('m', strtotime ( '-1 month' , strtotime ( $date )));
$futuremonth = date ('m', strtotime ( '+1 month' , strtotime ( $date )));
echo $priormonth;  // this will equal 12
echo "<br/>";
echo $futuremonth;  // this will equal 02

当一个月有31天时(如前面提到的ALeX inSide),"-1个月"解决方案是不可靠的。这里有一个函数,它返回给定日期之前任何所需月数的日期:(它实际上返回第一天的日期)

function getAnyPreviousMonthDate( $monthsBefore = null, $startDate = null )
{
  $monthsBefore = $monthsBefore ?? 1; //php7
  $monthsBefore = abs($monthsBefore);
  $c = $startDate ?? date('Y-m-d');
  for($i==0; $i<$monthsBefore; $i++) {
     $c = date('Y-m-d', strtotime('first day of previous month '.$c));
  }
  return $c;
}

所以如果我们这样称呼它:

echo getAnyPreviousMonthDate(3);
// we will get the first day of past 3 months from now
echo getAnyPreviousMonthDate(1, '2015-10-31');
// will return: '2015-09-01'