2011-08-15 16 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"); 

by

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

documentationを見て、2番目のパラメータ(「$ 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 month1 Octoberになることも同じです。

さまざまな方法がありますが、そのうちの1つは、適切に(少し使用された)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

私はサラセの答えが実際にオエジーの答えで指摘したのと同じ問題になるかもしれないと思います。彼は$ day-> format( 'd')を日の数字としてsetDate()に渡しましたが、対象月が30日しかない場合には意味をなさない31日の月になりました。私はあなたが正気ではない日付を設定しようとすると、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')); 
関連する問題