2016-12-23 79 views
1

为什么此代码无法按计划运行?多次加入月份不起作用

代码:

$regDate = '2016-10-03'; 
    echo $date1 = date('m', strtotime('+4 month', strtotime($regDate))); echo '<br>'; 
    echo $date2 = date('m', strtotime('+4 month', strtotime($date1))); echo '<br>'; 
    echo $date3 = date('m', strtotime('+4 month', strtotime($date2))); echo '<br>'; 
    echo $date4 = date('m', strtotime('+4 month', strtotime($date3))); echo '<br>'; 

我回来:

+0

你有没有使用'YYYY-MM-DD'格式的日期试过吗? –

+0

我需要它只给月 –

回答

1

这是无法识别的日期。你需要先计算日期然后echo他们。

$regDate = '2016-10-03'; 
$date1 = strtotime('+4 month', strtotime($regDate)); 
echo date('m', $date1) . '<br>'; 
$date2 = strtotime('+4 month', $date1); 
echo date('m', $date2) . '<br>'; 
$date3 = strtotime('+4 month',$date2); 
echo date('m', $date3) . '<br>'; 
$date4 = strtotime('+4 month', $date3); 
echo date('m', $date4) . '<br>'; 

另一种简单的方法是 - - 与尝试

$regDate = strtotime('2016-10-03'); 
foreach(range(1, 4) as $val) { 
    $regDate = strtotime('+4 month', $regDate); 
    echo date('m', $regDate) . '<br>'; 
} 

输出

02 
06 
10 
02 
+0

这是它的感谢! –

+0

用循环检查方法。这更容易和更简单。 –

+0

非常感谢:) –