phpで相対的な日時を得る方法のメモ。昨日明日、先月来月、次の日曜前の日曜、3分前、10分後など、現在日時を起点にしたあらゆるパターンの日時が得られる。

strtotime()はUnixタイムスタンプを返す組み込み関数。日時の文字列を渡すとそれに応じたUNIXタイムスタンプを返してくれる。

strtotime( "1999-12-31 23:59:59" );//946652399

で、strtotime()は日時以外に、様々な相対日時を指定可能になっている。strtotime( "yesterday" )とやると前日の午前0時0分0秒のUNIXタイムスタンプが返ってくる。これをdate()関数と組み合わせて使うことで、相対日時を簡単に取得することができる。

date( "Y-m-d H:i:s" , strtotime( "yesterday" ) );//ex 2011-10-27 00:00:00

以下はstrtotime()で使える日時指定のリスト。

現在日時
strtotime( "now" );
昨日明日、一昨日、明後日など前後の日付
strtotime( "+1 day" );//明日
strtotime( "+2 day" );//明後日
strtotime( "+10 day" );//10日後
strtotime( "+365 day" );//365日後

strtotime( "1 day" );//+は省いても構わない

strtotime( "-1 day" );//昨日
strtotime( "-2 day" );//一昨日
strtotime( "-10 day" );//10日前
strtotime( "-365 day" );//365日前
昨日今日明日の0時0分0秒
strtotime( "today" );//今日の0時0分0秒
strtotime( "yesterday" );//昨日の0時0分0秒
strtotime( "tomorrow" );//明日の0時0分0秒

strtotime( "yesterday 15:00:00" );//昨日の15時0分0秒
strtotime( "+1 day" )が現在時のちょうど24時間後になるのに対し、strtotime( "tomorrow" )だと明日の0時0分0秒が得られる。たまにstrtotime( "tomorrow" )strtotime( "+1 day" )は同じと書いているのを見かけるが間違い。異なった数値が返ってくるので使い分ける。strtotime( "now" ) - strtotime( "today" )で今日が始まって何秒経過したとかできて便利。
正午
strtotime( "noon" );//今日の12時0分0秒

strtotime( "yesterday noon" );//昨日正午
strtotime( "+1 week" );//1週間後
strtotime( "+10 week" );//10週後
strtotime( "-1 week" );//1週間前
strtotime( "-10 week" );//10週前
strtotime( "+1 month" );//来月
strtotime( "+2 month" );//再来月
strtotime( "-1 month" );//先月
strtotime( "-2 month" );//2カ月前

strtotime( "first day of january" );//今年の1月1日0時0分0秒。
strtotime( "last day of january" );//今年の1月1日0時0分0秒。
strtotime( "first day of next month" );//来月1日0時0分0秒。
strtotime( "january" );//今日が28日だとすると、今年の1月28日の0時0分0秒。
strtotime( "+1 year" );//1年後
strtotime( "-1 year" );//1年前
曜日
strtotime( "next sunday" );//次の日曜の0時0分0秒
strtotime( "+2 sunday" );//次の次の日曜0時0分0秒
strtotime( "last sunday" );//前の日曜の0時0分0秒
strtotime( "-3 sunday" );//3回前の日曜0時0分0秒

strtotime( "next sun" );//略称でもOK

strtotime( "first sun of 2011-10" );//指定した月の最初の日曜の日付。時間は0時0分0秒
strtotime( "second sun of 2011-10" );//指定した月の2つめの日曜の日付
strtotime( "last sun of 2011-10" ) );//指定した月の最後の日曜の日付
strtotime( "first sun of october 2011" );//この書き方でもOK
時分秒
strtotime( "+5 sec" );//5秒後
strtotime( "+5 min" );//5分後
strtotime( "+1 hour" );//1時間後
strtotime( "-5 sec" );//5秒前
strtotime( "-5 min" );//5分前
strtotime( "-1 hour" );//1時間前

strtotime( "+5 second" );//秒はsec・secondどちらでも可
strtotime( "+5 minute" );//分もmin・minuteどちらも可
組み合わせ
strtotime( "+1 month +1 day +1 hour +1 minute" );//1カ月と1日と1時間1分後
カテゴリー
PHP
投稿日
2011年10月28日

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>