0

我有两个对象 $o_NewRegDate(注册日期)和 $o_NewNowDate(当前日期)。

如果我们为 $o_NewRegDate 转储年份和月份:

var_dump (date_format($o_NewRegDate, 'Y-m'));

string '2009-09' (length=7)

如果我们为 $o_NewNowDate 转储年份和月份:

var_dump (date_format($o_NewNowDate, 'Y-m'));

    string '2013-09' (length=7)

在达到 $o_NewRegDate 的年份和月份之前,减少 $o_NewNowDate 中的月份的最佳方法是什么(将每个迭代存储在一个数组中)?

所需的输出数组将是这样的:

array (size=61)
  '2013-09-01' => string '09-2013' (length=7)
  '2013-08-01' => string '08-2013' (length=7)
  '2013-07-01' => string '07-2013' (length=7)
  (...)
  '2010-01-01' => string '01-2010' (length=7)
  '2009-12-01' => string '12-2009' (length=7)
  '2009-11-01' => string '11-2009' (length=7)
  '2009-10-01' => string '10-2009' (length=7)
  '2009-09-01' => string '09-2009' (length=7)
4

3 回答 3

1
$o_NewRegDate = '2009-09-01'; $o_NewNowDate = '2013-09-01'; 
$iDateStart = strtotime( $o_NewRegDate  );
$iDateEnd = strtotime( $o_NewNowDate );
$iEnd = ( $iDateEnd - $iDateStart ) / 2678400; //60*60*24*31
$aDate = array();
for( $i = 0; $i <= $iEnd; $i++ ) {
   $aDate[] = date('Y-m-d', strtotime('+'. $i .' month', $iDateStart));
}
$aDate = array_reverse( $aDate );

自己改进,尤其是 $iEnd 变量。

于 2013-09-18T07:58:04.870 回答
0
$o_NewRegDate = '2009-09-01';
$o_NewNowDate = '2013-09-18';

$startDate = new \DateTime($o_NewNowDate);
echo 'Start date: ', $startDate->format('Y-m-d') , PHP_EOL;
$endDate = new \DateTime($o_NewRegDate);
echo 'End date: ', $endDate->format('Y-m-d') , PHP_EOL;

$interval = new \DateInterval('P1M');
$monthPeriod = new \DatePeriod ($endDate, $interval, $startDate);

foreach ($monthPeriod as $key => $monthDate) {
   echo $monthDate->format('Y-m') , PHP_EOL;
}
于 2013-09-18T08:06:21.947 回答
0

使用这个简单的代码。

$date2='2014-07-12';
$monthArr=explode('-',$date2);
$numDays=cal_days_in_month(CAL_GREGORIAN, $monthArr[1], $monthArr[2]);
$tempDate=date('Y-m-d',strtotime($date2));
$regDate=date('Y-m-d',strtotime("-$numDays days",strtotime($tempDate)));
于 2014-07-12T12:24:40.243 回答