適当なC#の万年カレンダー


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace calendar
{
class Program
{
static void Main(string[] args)
{
int year, month;
int week;
int month_days;

Console.Write("年:");
year = int.Parse(Console.ReadLine());

Console.Write("月:");
month = int.Parse(Console.ReadLine());

switch (month)
{
case 2:
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
{
month_days = 29;
}
else
{
month_days = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
month_days = 30;
break;
default:
month_days = 31;
break;
}

if (month == 1 || month == 2)
{
year--;
month += 12;
}
week = (year + year / 4 - year / 100 + year / 400 +
(13 * month + 8) / 5 + 1) % 7;

Console.WriteLine("日\t月\t火\t水\t木\t金\t土");
for (int i = 1; i <= week + month_days; i++)
{
if (i <= week)
{
Console.Write("\t");
}
else
{
Console.Write("{0}\t",i - week);
}

if(i%7==0)
{
Console.Write("\n");
}
}
Console.Write("\n");
}
}
}

暇だったので適当に作ってみました。

月日数判定は定番の「西向く侍」で処理してます・・・というかこの方法しかないんですけどね。
グレゴリオ暦の法則に従って4で割り切れる年数で100で割りきれない年もしくは400で割り切れる年を閏年にするという例外処理を突っ込んでます。

あとは、1日の曜日分ずらして出力してしまえば完了。
Console.Writeだと改行なし、Console.WriteLineだと改行付きになるので、その点に注意すれば出力ストリームの処理は楽です。

ただ、改行するだけの場合
・Console.Write("\n");

・Console.WriteLine("");
のどっちが正しいのか未だにわからない・・・。

祝日処理を入れる場合は・・・総当たりしかない(汗
・月日固定
・第●○曜日
・1回しか存在しない
の3パターンがあるのでちょっと煩雑になりますが・・・。