LoginSignup
2
1

More than 1 year has passed since last update.

PHPのdate関数、timestampを使って2021/01/01から12/31までのカレンダーを作ってみる。

Last updated at Posted at 2021-05-14

date関数

日付とか時刻を返してくれる関数です。試しに色々と書いてみます。

print(date('G時i分s秒')."\n");
->4時47分57秒

print(date('Y/n/j')."\n");
->2021/5/14

print(date('Y F,j')."\n");
->2021 May,14

print(date('n/j(D)')."\n");
->5/14(Fri)

こんな感じになります。
date関数のパラメータ(GとかY,n,jなどは下記のqiitaなどを参照してください。
https://qiita.com/shuntaro_tamura/items/b7908e6db527e1543837

date関数の引数

date関数のリファレンスでdate関数の書式を確認してみます。

date ( string $format , int|null $timestamp = null ) : string

これはdate関数が日時をどう表すのかのフォーマットです。
第二引数にタイムスタンプなるものが指定されています。
ではこのタイムスタンプとは何か。

タイムスタンプ

タイムスタンプとは1970年01月01日から数えられている秒数を表しています。
今日現在のタイムスタンプは1620950400で1970年01月01日から1620950400経ったことを意味してます。

strtotime関数

文字列をタイムスタンプに変換してくれる関数です。

(文字列) (を) (タイムスタンプ)
string to timestamp = str to time = srttotime

//今日のタイムスタンプ
print(strtotime(today));
-> 1620950400

//2日後のタイムスタンプ
print(strtotime('+2day');

//信長が光秀に殺された日
print(strtotime('1582-6-21'));
-> -12229315200

こんな感じです。

date関数の引数にタイムスタンプを渡してみる。

date関数の引数にタイムスタンプを渡してみるとどうなるか実際に確認してみます。

print(date('Y/n/j', 86400));
->1970/1/2

print(date('Y/n/j', 72800));
->1970/1/3

これはタイムスタンプに86400秒を指定しています。これはつまり24時間後なので、タイムスタンプを数え始めた1970年1月1日の24時間後の日付を出力しています。2番目のprintは72時間後の1月3日です。

ではこれを元に2021/01/01のタイムスタンプと12/31のタイムスタンプを取得して、後はループで86400秒、つまり1日置きにループしたいと思います。

//2021年1月1日のタイムスタンプを取得
$first_date = strtotime('2021-01-01');

//2021年12月31日のタイムスタンプを取得
$end_date = strtotime('2021-12-31');

//$first_dateが$end_dateより大きくなるまで86400秒を足して1日後を表示する
for($i=$first_date; $i<=$end_date;$i = $i + 86400){
    print(date('Y/n/d(D)'."\n", '+'.$i.'day'));
}

これで表示結果が
2021/1/01(Fri)
2021/1/02(Sat)
2021/1/03(Sun)
2021/1/04(Mon)
2021/1/05(Tue)
2021/1/06(Wed)
2021/1/07(Thu)
2021/1/08(Fri)
2021/1/09(Sat)
.
.
.
2021/12/30(Thu)
2021/12/31(Fri)

と表示されるはずです。

2
1
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
2
1