3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

strtotime() を使った曜日による相対的な日付取得

Last updated at Posted at 2017-11-21

strtotime() で相対的な曜日による日付取得をしようとすると挙動が少しややこしいので、色々なパターンで相対的な月曜日を取得したときの結果をメモしておきます。

検証コード

以下の3日間で検証してみます。

  • 2017-11-19 (日曜日)
  • 2017-11-20 (月曜日)
  • 2017-11-21 (火曜日)

これらの日付に対して以下のパターンで相対的な月曜日を取得してみます。

  • monday last week
  • last monday
  • monday this week
  • monday
  • next monday
  • monday next week
$results = [];

foreach (['2017-11-19', '2017-11-20', '2017-11-21'] as $date) {
    foreach (['monday last week', 'last monday', 'monday this week', 'monday', 'next monday', 'monday next week'] as $rel) {
        $results[$date][$rel] = date('Y-m-d', strtotime($rel, strtotime($date)));
    }
}

var_dump($results);

検証コードの実行結果

11月19日 (日) 11月20日 (月) 11月21日 (火)
monday last week 11月6日 11月13日 11月13日
last monday 11月13日 11月13日 11月20日
monday this week 11月13日 11月20日 11月20日
monday 11月20日 11月20日 11月27日
next monday 11月20日 11月27日 11月27日
monday next week 11月20日 11月27日 11月27日

ポイント

  • 月曜日当日に monday として取得した場合は今日 (今週の月曜日) が取得される。
  • 月曜日当日に next monday として取得した場合は7日後 (来週の月曜日) が取得される。
  • 月曜日当日に last monday として取得した場合は7日前 (先週の月曜日) が取得される。

つまり月曜日当日に実行した場合だけ last mondaynext monday の差が 7日 ではなく 14日 になります。

  • last weeknext week をつけるとその日からみた先週や来週の月曜日が取得される。
    • 週は月曜日始まりの日曜日終わり固定。
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?