カレンダー3

週間カレンダーを作成したので、今度は月刊カレンダーを作成する。

考え方は、今日の日付を取得し、そこから今日の月の末日を求める。
また、当月の1日の曜日を求め、曜日順に日付を埋めていく。

//つきカレンダーの作成
//mySmartyをrequire_once

$smarty = new MySmarty();

$week = array(
‘日’,
‘月’,
‘火’,
‘水’,
‘木’,
‘金’,
‘土’,
);
$smarty->assign( ‘week’, $week );

//表示時間を取得
$now = time();

$year = date(‘Y’, $now);
$month= date(‘m’, $now);
$day= date(‘d’, $now);
$smarty->assign( ‘year’, $year );
$smarty->assign( ‘month’, $month );
$smarty->assign( ‘day’, $day );

//今月の日数の取得
$month_dates = date(‘t’, $now);

//月の始めの時間取得
$month_startDate = strtotime( “{$year}/{$month}/1” );

//月はじめの曜日を取得
$month_startWeek = date( ‘w’, $month_startDate );

//月の週配列を作成
$month_date = array();

//月初めの週の空いている枠を埋める
for( $n = 0; $n < 7; $n ++ ){
$month_date[0][$n] = ‘&nbsp;’;
}

$weekOffset = date( ‘W’, $month_startDate );
for( $n = 1; $n <= $month_dates; $n ++ ){
$date = strtotime( “{$year}/{$month}/{$n}” );

$nWeek = date(‘W’, $date) – $weekOffset;

$w = date(‘w’, $date );
if( $w == 0 ) $nWeek ++;

//年末が月曜日移行の時、date(‘W’)の返り値が1となるので
//計算を補正する
//date関数の不具合かもしれない
if( $nWeek < 0 ){
$tmpDate = $date – ( $w * 24 * 3600 );
$nWeek = date(‘W’, $tmpDate ) – $weekOffset;
if( date(‘w’, $tmpDate ) == 0 ) $nWeek ++;
}

$month_date[$nWeek][$w] = $n;
}
//月終わりの空いている枠を埋める
$month_endDate = strtotime( “{$year}/{$month}/{$month_dates}” );
$month_endWeek = date(‘w’, $month_endDate );
if( $month_endWeek < 6 ){
$w = date(‘W’, $month_endDate) – $weekOffset;

//年末が月曜日移行の時、date(‘W’)の返り値が1となるので
//計算を補正する
if( $w < 0 ){
$tmpDate = $month_endDate – ($month_endWeek * 24 * 3600 );
$w = date( ‘W’, $tmpDate );
if( date(‘w’, $tmpDate) == 0 ){
$w ++;
}
$w -= $weekOffset;
}

for( $n = $month_endWeek+1; $n < 7; $n ++ ){
$month_date[$w][$n] = ‘&nbsp;’;
}
}
$smarty->assign( ‘month_date’, $month_date );

$smarty->display( ‘smarty01/lesson03.tpl’);

Smartyは…

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
<title>月のカレンダー表示</title>
<script type=”text/javascript”>

var _gaq = _gaq || [];
_gaq.push([‘_setAccount’, ‘UA-23421796-1’]);
_gaq.push([‘_trackPageview’]);

(function() {
var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
})();

</script>

</head>
<body>
<div style=”text-align:center;”>
<table border=”1″>
<tr>
<th colspan=”7″>{$year}年{$month}月</th>
</tr>
<tr>
{foreach from=$week item=node}<th style=”background-color:#A0FFA0;padding:3px;”>{$node}</th>{/foreach}

</tr>
{foreach from=$month_date item=weeks}
<tr>
{foreach from=$weeks item=node}<td style=”text-align:center;padding:3px;{if $node==$day}color:white;background-color:blue;{/if}”>{$node}</td>{/foreach}
</tr>
{/foreach}
</table>
</div>
</body>
</html>

となる。

そして、結果はこちら