基于第一个版本[C#可供查询的月历]做了一点小修改,让主函数中定义的变量更少,更简洁(https://blog.csdn.net/weixin_48343145/article/details/123514237?spm=1001.2014.3001.5502)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testFunction_1
{
class Program
{
static void Main(string[] args)
{
int year = 0;
int month = 0;
showMonthCalander(year, month);
Console.ReadLine();
}
private static int getWeekByDay(int year, int month, int day)
{
DateTime dt = new DateTime(year, month, day);
return (int)dt.DayOfWeek;
}
static int calculateDaysOfMonth(int year, int month)
{
bool leapYear;
if (year % 4 == 0 && year % 100 != 0)
{
leapYear = true;
}
else
leapYear = false;
if (month == 2)
{
if (leapYear)
{
return 29;
}
else return 28;
}
switch (month)
{
case 1: return 31;
case 3: return 31;
case 5: return 31;
case 7: return 31;
case 8: return 31;
case 10: return 31;
case 12: return 31;
case 11: return 30;
case 4: return 30;
case 6: return 30;
case 9: return 30;
}
return 1;
}
private static void showMonthCalander(int year, int month)
{
int i;
int dayNum = 1;
Console.WriteLine("请输入想查询的年份");
year = int.Parse(Console.ReadLine());
Console.WriteLine("请输入想查询的月份");
month = int.Parse(Console.ReadLine());
int firWeekday = getWeekByDay(year, month, 1);
int DaysOfMonth = calculateDaysOfMonth(year, month);
Console.WriteLine("日\t一\t二\t三\t四\t五\t六");
for (i = 0; i < firWeekday; i++)
{
Console.Write("\t");
}
while (i < 7)
{
if (i < 6)
{
Console.Write(dayNum++);
Console.Write("\t");
i++;
}
else
{
Console.Write(dayNum++);
Console.WriteLine("\r\n");
i = 0;
}
if (dayNum > DaysOfMonth)
{
break;
}
}
}
}
}