2011-08-15 59 views
1

我有以下说法。要么我从查询字符串中得到日期,要么我得到今天的日期。在php中添加日期

然后我需要获取当前的上一个月。

我觉得我用 “的strtotime”

$selecteddate = ($_GET ['s'] == "") 
    ? getdate() 
    : strtotime ($_GET ['s']) ; 


    $previousMonth = strtotime(date("Y-m-d", $selecteddate) . " +1 month"); 

    $previousMonthName = $previousMonth[month]; 
    print $previousMonthName; 
    $month = $selecteddate[month]; 

/*编辑脚麻*/

$selecteddate = ($_GET ['s'] == "") 
? getdate() 
: strtotime ($_GET ['s']) ; 

$previousMonth = strtotime(" -1 month", $selecteddate); 
$nextMonth = strtotime(" +1 month", $selecteddate); 


$previousMonthName = date("F",$previousMonth); //Jan 
$nextMonthName = date("F",$nextMonth); // Jan 
$month = $selecteddate[month]; // Aug 
+0

re。你的编辑; '$ selecteddate'将包含一个数组(从'getdate()'返回)或一个整数(从'strtotime()'返回)。如果传递数组,那么稍后调用strtotime()将不会感到满意。 – salathe

回答

2

你差不多吧 - 只需更换

$previousMonth = strtotime(date("Y-m-d", $selecteddate) . " +1 month"); 

通过

$previousMonth = strtotime(" +1 month", $selecteddate); 

查看documentation以了解有关第二个参数(称为“$ now”)的更多信息。得到月份名称,这样做(documentation again):

$previousMonthName = date("F",$previousMont); 
$month = date("F",$selecteddate); // not sure if you want to get the monthname here, 
            // but you can use date() to get a lot of other 
            // values, too 
+0

+1你打我吧:) –

+0

哇,照明快。谢谢 – frosty

+0

等我说了很快,见上面。它是否返回Jan,因为它没有正确传递? – frosty

1

oezi's answer会碰到对的几个月结束的问题。这是由于PHP对±1 month的解释,它只是简单地增加/减少月份,然后根据情况调整日期部分。

例如,给定31 October+1 month日期将成为31 November不存在。 PHP将此考虑在内,并将角色的日期定为。 -1 month同样会发生变为1 October

存在各种替代方法,其中一种是根据情况设置(使用少量)DateTime::setDate()明确修改日期。

// e.g. $selecteddate = time(); 

$now = new DateTime; 
$now->setTimestamp($selecteddate); 

// Clone now to hold previous/next months 
$prev = clone $now; 
$next = clone $now; 

// Alter objects to point to previous/next month 
$prev->setDate($now->format('Y'), $now->format('m') - 1, $now->format('d')); 
$next->setDate($now->format('Y'), $now->format('m') + 1, $now->format('d')); 

// Go wild 
var_dump($prev->format('r'), $next->format('r')); 
1

我认为萨拉思的答案可能实际上会落在他在oezi的回答中指出的同样的问题。他通过$ now-> format('d')将setDate()设置为日期编​​号,但在31天的月份中,如果目标月份只有30天,则可能无意义。我不确定SetDate会如何设置一个不理智的​​日期 - 很可能会引发错误。但解决方案非常简单。所有的月份都有第1天。这是我的salathe代码版本。

// e.g. $selecteddate = time(); 

$now = new DateTime; 
$now->setTimestamp($selecteddate); 

// Clone now to hold previous/next months 
$prev = clone $now; 
$next = clone $now; 

// Alter objects to point to previous/next month. 
// Use day number 1 because all the questioner wanted was the month. 
$prev->setDate($now->format('Y'), $now->format('m') - 1, 1); 
$next->setDate($now->format('Y'), $now->format('m') + 1, 1); 

// Go wild 
var_dump($prev->format('r'), $next->format('r'));