PHPでマンスリーカレンダー
月間表示形式のカレンダーを生成
PHP
/**
*
* PHPでマンスリーカレンダー
*
* @param int $year
* @param int $month
* @param int $day
* @return array
*/
function getCalendarMonthly($year, $month, $day)
{
// 先月の日付
$before_days = date('w', mktime(0, 0, 0, $month, 1, $year)) - 1;
for ($i = $before_days; $i > 0; $i--){
$calendar[] = array(date('Y-m-d', mktime(0, 0, 0, $month, 1 - $i, $year)), 'last_month');
}
// 今月の日付
$total = date('t', mktime(0, 0, 0, $month, 1, $year));
for ($i = 1; $i <= $total; $i++){
$calendar[] = array(sprintf('%s-%02d-%02d', $year, $month, $i), 'this_month');
}
// 来月の日付
$after_days = 8 - date('w', mktime(0, 0, 0, $month + 1, 1, $year));
for ($i = 0; $i < $after_days; $i++){
$calendar[] = array(date('Y-m-d', mktime(0, 0, 0, $month + 1, 1 + $i, $year)), 'next_month');
}
// 今日(指定日)
$today = sprintf('%s-%02d-%02d', $year, $month, $day);
// 先月
$last_day = date('Y-m-d', mktime(0, 0, 0, $month - 1, 1, $year));
// 来月
$next_day = date('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year));
return array($calendar, $today, $last_day, $next_day);
}
指定日が2013-01-15の場合は、2012-12-31~2013-02-03が配列にセットされる。
Array
(
[0] => Array
(
[0] => Array
(
[0] => 2012-12-31
[1] => last_month
)
[1] => Array
(
[0] => 2013-01-01
[1] => this_month
)
[2] => Array
(
[0] => 2013-01-02
[1] => this_month
)
(略)
[32] => Array
(
[0] => 2013-02-01
[1] => next_month
)
[33] => Array
(
[0] => 2013-02-02
[1] => next_month
)
[34] => Array
(
[0] => 2013-02-03
[1] => next_month
)
)
[1] => 2013-01-15
[2] => 2012-12-01
[3] => 2013-02-01
)
Smarty
<table>
<caption>
<a href="/monthly/{$last_day|date_format:'%Y-%m'}"><</a>
<a href="/monthly/{$today|date_format:'%Y-%m'}">{$today|date_format:'%Y/%m'}</a>
<a href="/monthly/{$next_day|date_format:'%Y-%m'}">></a>
</caption>
<thead>
<tr>
<th>月</th>
<th>火</th>
<th>水</th>
<th>木</th>
<th>金</th>
<th>土</th>
<th>日</th>
</tr>
</thead>
<tbody>
{foreach $calendar as $calendarKey => $calendarVal}
{if $calendarVal@index % 7 == 0}
<tr>
{/if}
<td class="{$calendarVal[1]}{if $today == $calendarVal[0]} today{/if}"><a href="/monthly/{$calendarVal[0]}">{$calendarVal[0]|date_format:'%e'}</a></td>
{if $calendarVal@iteration % 7 == 0}
</tr>
{/if}
{/foreach}
</tbody>
</table>
<または先月の日付をクリックすると先月のカレンダーを表示。
>または来月の日付をクリックすると来月のカレンダーを表示。
サンプル