using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chapter7
{
class Program
{
static void Main(string[] args)
{
//打印日历
Console.WriteLine("请输入要打印日历的年份:");
int year = Convert.ToInt32(Console.ReadLine());
while (year<1900)
{
Console.WriteLine("请输入大于1900年份的整数:");
year = Convert.ToInt32(Console.ReadLine());
}
for (int i = 1; i < 13; i++)
{
int days = DateTime.DaysInMonth(year, i);//得到当前年/月的天数
DateTime currday=new DateTime(year,i,1);//当月第一天
DateTime lastday = currday.AddMonths(1);//下月第一天
Console.WriteLine();
switch (i)//判断月份,显示不同的前景色
{
case 1:
Console.ForegroundColor = ConsoleColor.Red;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Blue;
break;
case 3:
Console.ForegroundColor = ConsoleColor.Cyan;
break;
case 4:
Console.ForegroundColor = ConsoleColor.DarkBlue;
break;
case 5:
Console.ForegroundColor = ConsoleColor.DarkCyan;
break;
case 6:
Console.ForegroundColor = ConsoleColor.DarkGreen;
break;
case 7:
Console.ForegroundColor = ConsoleColor.DarkMagenta;
break;
case 8:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 9:
Console.ForegroundColor = ConsoleColor.DarkYellow;
break;
case 10:
Console.ForegroundColor = ConsoleColor.Green;
break;
case 11:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 12:
Console.ForegroundColor = ConsoleColor.White;
break;
}
Console.WriteLine("{0}年{1}月",year,i);
Console.WriteLine("周日\t周一\t周二\t周三\t周四\t周五\t周六");
while (currday<lastday)
{
int weekday =Convert.ToInt32(currday.DayOfWeek);//得到日期是星期几
if (currday.Day == 1)//判断该月第一天
{
StringBuilder tmpSpace = new StringBuilder();
for (int j = 0; j < weekday; j++)//输出制表符
{
tmpSpace.Append(" \t");
}
Console.Write("{0} {1}", tmpSpace.ToString(), currday.Day);
}
else if (currday.DayOfWeek == DayOfWeek.Sunday)//如果是礼拜天
{
Console.Write(Environment.NewLine);
Console.Write(" {0}", currday.Day);
}
else
{
Console.Write(" \t {0}", currday.Day);
}
currday = currday.AddDays(1);
}
}
Console.Read();
}
}
}
显示结果: