PHP date関数を使っていろんな日付を取得する

2018.10.13

はじめに

php の date()関数と strtotime()関数を使って前日翌日などの日付を取得する方法を紹介します。

今日の日付

date()関数に日付の形式を指定すると今日の日付を取得することができます。

$today = date('Y-m-d');

下記のようにすると時間迄取得できます。

$today = date('Y-m-d H:i:s');

指定日でいろいろな日付を取得したい場合は下記のようにすると取得できます。

$today = '2018-01-01';

前日翌日

$today = date('Y-m-d');
echo date('Y-m-d', strtotime("-1 day", strtotime($today)));
echo date('Y-m-d', strtotime("1 day", strtotime($today)));

前月翌月

$today = date('Y-m-d');
echo date('Y-m-d', strtotime("-1 month", strtotime($today)));
echo date('Y-m-d', strtotime("1 month", strtotime($today)));

月初月末

$today = date('Y-m-d');
echo date('Y-m-d', strtotime('first day of ' . $today));
echo date('Y-m-d', strtotime('last day of ' . $today));

翌月月初月末

$today = date('Y-m-d');
echo date('Y-m-d', strtotime('first day of ' . date('Y-m-d', strtotime('1 month', strtotime($today)))));
echo date('Y-m-d', strtotime('last day of ' . date('Y-m-d', strtotime('1 month', strtotime($today)))));

こちらの方法でも取得できます。

echo date('Y-m-d', strtotime('first day of next month', strtotime($today)));
echo date('Y-m-d', strtotime('last day of next month', strtotime($today)));

n ヶ月前月初月月末

$today = date('Y-m-d');
echo date('Y-m-d', strtotime('first day of ' . date('Y-m-d', strtotime('-2 month', strtotime($today)))));
echo date('Y-m-d', strtotime('last day of ' . date('Y-m-d', strtotime('-2 month', strtotime($today)))));

echo date('Y-m-d', strtotime('first day of ' . date('Y-m-d', strtotime('2 month', strtotime($today)))));
echo date('Y-m-d', strtotime('last day of ' . date('Y-m-d', strtotime('2 month', strtotime($today)))));

曜日を取得する

date('w')のように「w」を指定すると 0 から 6 までの曜日に対応する数値が取得できます。
これを利用して曜日の配列から日本語の曜日を取得します。

$week = array(
    0 => '日',
    1 => '月',
    2 => '火',
    3 => '水',
    4 => '木',
    5 => '金',
    6 => '土',
);
$today = date('w');
echo $week[$today];

指定日の曜日を取得したい場合は、下記のようにすると良いでしょう。

$today = date('w', strtotime('2018-01-01'));