LoginSignup
0
1

More than 5 years have passed since last update.

DatePeriodクラスを使ってカレンダーに必要な値を取得

Posted at

DatePeriodクラスを使って日付のレンジを指定

DatePeriodクラスを使うことによって、日付のデータをまとめて取得することができる。 

calendar.php
$period = new DatePeriod(
   new DateTime('first day of this month'),
   new DateInterval('P1D'),
   new DateTime('first day of next month')
);
//今月の月初から月末までの日付データを取得することができる

第1引数ではDateTimeクラスを使っていつの日付からデータを取得するか指定、第2引数ではDateIntervalクラスを使って何日間隔で日付データを取るかを指定、そして第3引数では同じくDateTimeクラスを使って、いつまでの日付を取得するかを指定しています。 

第3引数がnext monthになっている理由は、’last day of this month’にしてしまうと、月末日を取得できない為です。 なので月内の日付を全て取得したい場合は、上記のように書きます。 

DateTimeオブジェクト操作する 

繰り替えし処理を使い日付データを取り出していきます。

calendar.php
foreach($period as $day){
   echo $day->format('d');
}
//0102030405060708091011121314151617....

formatはDateTimeクラスに用意されているメソッドになっており、決められた書式でデータを返してくれる。 

公式サイトにまとまっているので、以下を参考に引数を設定してあげればいい。

formatに関する公式サイト

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