分かっちゃえば怖くないんだけども。
要するにの話
date形式っていうのは「2000-01-01」みたいな形になる。
結果こうなればいいという話で、手段は問われない。
現在の年月日を出したい場合はこうなる。
print date('Y-m-d'); //2024-03-15
print date('Y/m/d'); //2024/03/15
Officeの日付設定に似てる。
月初はこんな感じにできる。
print date('Y-m-01'); //2024-03-01
月初は必ず「01」だから代入しちゃえっていう乱暴な方法。
月末が厄介。28(29)、30,31があるからね。
strtotime()を使うとその辺りをクリアしつつ、更に凝ったことができる。年月日時分秒、週、曜日、なんでも英文で指定できちゃうっていう、かなりぶっ飛んだ仕様。
print date('Y-m-d', strtotime('first day of this month'.date('Y-m-d'))); //2024-03-01
print date('Y-m-d', strtotime('last day of this month'.date('Y-m-d'))); //2024-03-31
翌月末はこう。
print date('Y-m-d', strtotime('last day of next month'.date('Y-m-d'))); //2024-04-30
先月末。
print date('Y-m-d', strtotime('last day of last month'.date('Y-m-d'))); //2024-02-29
数字でも指定できる。
print date('Y-m-d', strtotime('-1 month'.date('Y-m-d'))); //2024-02-15
print date('Y-m-d', strtotime('+3 day'.date('Y-m-d'))); //2024-03-18
なんかもうすごい。
便利だけどなんかこう、キモい。怖い。
もっと作例を見たい人はこちら。
日時を取得 - 明日、昨日、来週、先週、来月、先月、来年、去年 - date() strtotime() - PHP入門 - Webkaru
ここでは関数 date() と strtotime() を使って、さまざまな日時を取得するサンプルコードを紹介します。
コメント