2011-08-15 56 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'));