その月の日付かどうかを判別する

広告

「Calendar_Month_Weekdays」クラスのオブジェクトから「Calendar_Day」クラスのオブジェクトを取得した場合、月の最初と最後に前月や次月の日付も含まれる場合があります。そこで対象となっている月の日付なのかどうかを判別する方法を確認します。「Calendar_Day」クラスで用意されている「isEmpty」メソッドを使います。

戻り値:
  Day オブジェクトが別の月の日である場合に true

実際には次のように記述します。

$month = new Calendar_Month_Weekdays(2007, 6, 0);
$month -> build();

while ($day = $month -> fetch()){
  if ($day -> isEmpty()){
    ....
  }else{
    ....
  }
}

前月や次月のオブジェクトの場合には「isEmpty」メソッドが「true」を返します。

サンプルプログラム

では簡単なサンプルで実際に試してみます。

sample11-1.php

<html>
<head>
<title>PHP TEST</title>

<style type="text/css">
td{
border:solid 1px #999999;
text-align:right;
padding:5px;
}
</style>

</head>
<body>

<p>表形式で日付を取得</p>

<?php
require_once("Calendar/Month/Weekdays.php");

$month = new Calendar_Month_Weekdays(2007, 5, 0);
$month -> build();

print("<p>2007年5月</p>");
print("<table>");
print("<tr><th>日</th><th>月</th><th>火</th><th>水</th><th>木</th><th>金</th><th>土</th></tr>");
while ($day = $month -> fetch()){
  if ($day -> isFirst()){
    print("<tr>");
  }

  if ($day -> isEmpty()){
    print("<td> </td>");
  }else{
    if ($day -> isFirst()){
      print("<td style=¥"color:#ff0000¥">".$day->thisDay()."</td>");
    }else if ($day -> isLast()){
      print("<td style=¥"color:#0000ff¥">".$day->thisDay()."</td>");
    }else{
      print("<td>".$day->thisDay()."</td>");
    }
  }

  if ($day -> isLast()){
    print("</tr>");
  }

}
print("</table>");

?>
</body>
</html>

上記をWWWサーバに設置しブラウザで見てみると下記のように表示されます。

その月の日付かどうかの判別を行う

( Written by Tatsuo Ikura )