2013-01-23 26 views
0

我有以下功能,只从当前的月份拉评论。我需要它不会从下个月收到任何评论。PHP增加1个月,但考虑到年度变化

我有下个月定义为$to_date+1我怎么能改变这个自动计算出它在下一年,即防止它在第13个月?谢谢

Function to only pull comments from a date range of the current month 
    $from_date = date('Y-m') . '1 00:00:00'; 
    $to_date = date('m') . '1 00:00:00'+1; 
    $all_comments = Comment::find('all', 
    array(
     'conditions'=>array('response_date_and_time >= ? AND response_date_and_time <= ?', $from_date, $to_date) 
    ) 
); 
+1

使用mysql日期函数此 – 2013-01-23 03:32:22

回答

2

strototime可以为你做这个。您可以使用关键字“now + 1 month”,将当前日期+1并返回unix时间戳,日期函数将转换为正确的月份。应该返回02

$to_date = date('m', strtotime('now + 1 month')); 
1

有两种方法。正如已经提到的,你可以使用的strtotime:

$to_date = date('m', strtotime('now + 1 month')) . ' 00:00:00'; 

但我认为这也可能是一个好主意,你要了解模运算%。基本上,模数将返回除法后的余数(在PHP中,这是一个整数,在其他语言(如JavaScript)中它也会包含任何小数值)。在这种情况下,这意味着我们有一个快速简便的方法,以确保一个月换到从未高于12

// get the modulus 
$dt = ((date('m')+1)%12); 
// bit of a trick. December is the 12th month. 12 % 12 is 0, which is invalid 
// so we check to see if the month is 0, and if it is we use 12 instead. 
$to_date = ($dt?$dt:12) . ' 00:00:00'; 
+0

感谢约模量信息。干杯 –