̃Gg[͂ĂȃubN}[Nɒlj

PHP :: イディオム / strtotime を使った相対的な日付



strtotime

英文形式の日付を Unix タイムスタンプに変換する

int strtotime ( string $time [, int $now ] )

time
パースする文字列。PHP 5.0.0 より前のバージョンではマイクロ秒を含めることはできませんでした。 PHP 5.0.0 以降ではマイクロ秒を含めることが可能ですが、その値は無視されます。

now
返される値を計算するために使用されるタイムスタンプ。

戻り値

成功時はタイムスタンプ、そうでなければ FALSE を返します。 PHP 5.1.0 以前ではこの関数は失敗時に -1 を返します。


yesterday / tomorrow : 昨日 / 明日

// 昨日
echo '昨日: '.date('Y-m-d', strtotime('yesterday')).PHP_EOL;
 
// 明日
echo '明日: '.date('Y-m-d', strtotime('tomorrow')).PHP_EOL;


day : 日

// 10日前
echo '10日前: '.date('Y-m-d', strtotime('-10 day')).PHP_EOL;
 
// 10日後
echo '10日後: '.date('Y-m-d', strtotime('+10 day')).PHP_EOL;


week : 週

// 1週間前
echo '1週間前: '.date('Y-m-d', strtotime('-1 week')).PHP_EOL;
 
// 1週間後
echo '1週間後: '.date('Y-m-d', strtotime('+1 week')).PHP_EOL;


last / next : 前回 / 次回

// 前回の日曜日
echo '前回の日曜日: '.date('Y-m-d', strtotime('last Sunday')).PHP_EOL;
 
// 次回の日曜日
echo '次回の日曜日: '.date('Y-m-d', strtotime('next Sunday')).PHP_EOL;
バージョン 4.4.0 より前の PHP では、”next” が誤って +2 として計算されます。これを解決するには、代わりに ”+1” を使用します。


month : 月

// 先々月
//echo '先々月: '.date('Y-m', strtotime('-2 month')).PHP_EOL; // NG
echo '先々月: '.date('Y-m', strtotime(date('Y-m-1').'-2 month')).PHP_EOL;
 
// 先月
//echo '先月: '.date('Y-m', strtotime('-1 month')).PHP_EOL; // NG
echo '先月: '.date('Y-m', strtotime(date('Y-m-1').'-1 month')).PHP_EOL;
 
// 今月
echo '今月: '.date('Y-m').PHP_EOL;
 
// 来月
//echo '来月: '.date('Y-m', strtotime('+1 month')).PHP_EOL; // NG
echo '来月: '.date('Y-m', strtotime(date('Y-m-1').'+1 month')).PHP_EOL;
 
// 再来月
//echo '再来月: '.date('Y-m', strtotime('+2 month')).PHP_EOL; // NG
echo '再来月: '.date('Y-m', strtotime(date('Y-m-1').'+2 month')).PHP_EOL;
  • strtotime(date('Y-m-1').'…')) としている理由については以下を参照してください。

PHPで、先月、翌月などのを扱うときの注意



デモ

以下は、本日 2024-04-19 を基準にして、相対的に日付を取得しています。

昨日2024-04-18strtotime('yesterday')
明日2024-04-20strtotime('tomorrow')
10日前2024-04-09strtotime('-10 day')
10日後2024-04-29strtotime('+10 day')
1週間前2024-04-12strtotime('-1 week')
1週間後2024-04-26strtotime('+1 week')
前回の日曜日2024-04-14strtotime('last Sunday')
次回の日曜日2024-04-21strtotime('next Sunday')
先々月2024-02strtotime(date('Y-m-1').'-2 month')
先月2024-03strtotime(date('Y-m-1').'-1 month')
今月2024-04
来月2024-05strtotime(date('Y-m-1').'+1 month')
再来月2024-06strtotime(date('Y-m-1').'+2 month')









programming/php/idiom/strtotime.txt