eyecatch php

PHP

【PHP】strtotime関数の使い方サンプル9個

2018/04/14

PHPのタイムスタンプ系の関数、strtotime()の使い方をよく調べるので、忘備録代わりに残してみます。

strtotime()の使い方まとめ

仕様

【書式】
[php]$result = strtotime($time, $now=time());[/php]

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

$result : UNIXタイムスタンプ
$time : 日付/時刻の書式(’Y-m-d’等)
$now : 返される値を計算するために使用されるタイムスタンプ

strtotime()のいろんな使い方

例1)現在のUNIXタイムスタンプ形式値を取得

[php]$timestamp_now strtotime("now");[/php]

例2)2日前のUNIXタイムスタンプ形式値を取得

[php]$timestamp_2days_ago = strtotime("-2 day");[/php]

例3)1週間後のUNIXタイムスタンプ形式値を取得

[php]$timestamp_1week_later = strtotime("+1 week");[/php]

例4)3ヶ月前のUNIXタイムスタンプ形式値を取得

[php]$timestamp_3month_ago = strtotime('- 3 month');[/php]

例5)1週間2日3時間4分5秒後のUNIXタイムスタンプ形式値を取得

[php]$timestamp_1w2e3h4m5s_later = strtotime("+1 week 2 days 3 hours 4 minute 5 seconds");[/php]

例6)次の水曜日のUNIXタイムスタンプ形式値を取得

[php]$timestamp_next_wednesday strtotime("next Wednesday");[/php]

例7)前の金曜日のUNIXタイムスタンプ形式値を取得

[php]$timestamp_last_friday = strtotime("last Friday");[/php]

例8)指定した日付の、翌日を取得

[php]$next_day = date("Y/m/d", strtotime("+1 day", strtotime("2014/06/23")));[/php]

これで "2014/06/24" の日付が取得できます。

例9)指定した日付の、三日前を取得

[php]$next_day = date("Y/m/d", strtotime("-3 day", strtotime("2014/06/23")));[/php]

例8)と同じく、これで "2014/06/20" の日付が取得できます。
ただし1ヶ月とか長いスパンで、俗にいう「西向く侍」(2月・4月・6月・9月・11月)が含まれる場合はズレる恐れがあるので、よく確かめることが必要です。

-PHP
-, ,