0
0

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 3 years have passed since last update.

[PHP]365日+曜日を出力する

Last updated at Posted at 2020-09-07

今日の日付を出力するには下記のように記述する。

day.php
<?php
print(date('n/j(D)'));
?>

nは月を取得する
jは日付けを取得する
Dは英語の曜日(頭3文字)を取得する

timezoneの設定をしていなければ、直接記述することで変更できる。

day.php
<?php
date_default_timezone_set('Asia/Tokyo');
print(date('n/j(D)'));
?>

ここで、1日後の日付+曜日を取得するにはどうすれば良いか考える。

day.php
<?php
print(date('n/j(D)', strtotime('+1day'));
?>

これで1日後の日付+曜日を取得できた。

strtotimeとはString to Timestampの略で
文字列をTimestamp型に変換できるファンクションのこと。

+1dayなら1日後
-1dayなら1日前
+365dayなら1年後

とすることができる。

strtotime('+1day')

という部分をfor文を用いて365回繰り返せば良さそう。

day.php
<?php
for($i=1; $i<=365; $i++); {
  $date = strtotime('+' . $i . 'day');
  print(date('n/j(D)', $date));
  print "\n";
}
?>

これで365日分取得できました。


[ 解説 ]

①変数i=1として、365以下で繰り返し、毎回変数iに1を足す

for ($i=1; $i<=365; $i++);

$dateという変数にstrtotimeの中身を分解して代入

$date = strtotime('+' . $i . 'day');
//  strtotime('+1day')の、'+1day'の部分 1を$iとしている

strtotimeファンクションを記述していた部分に変数$dateを置く

print(date('n/j(D)', $date));

④見やすいように改行する

print "\n";

ちなみに、{}の部分は下記のように書き換えることもできる

day.php
<?php
for ($i=1; $i<=365; $i++):
  $date = strtotime('+' . $i . 'day');
  print(date('n/j(D)', $date));
  print "\n";
endfor;
?>

こちらの方が何に対する閉じタグなのかがわかりやすい。
while文も同じで下記のように記述できる。

while (....):
  ....
endwhile;

以上です。お疲れ様でした。

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?