Perpetual calendar - ASP.NETCORE writing method

Table of contents

Topic requirements:

Implementation code:

Code analysis:

Effect example:


Topic requirements:

Create a .NET Core console application to implement a perpetual calendar, and print out the calendar of the specified year and month in the console through the input year and month.

Implementation code:

//做一个万年历
Console.WriteLine("请输入年份:");
string year = Console.ReadLine();
Console.WriteLine("请输入月份:");
string month = Console.ReadLine();
//获取星期几,这个月多少天
DateTime dt = DateTime.Parse(string.Format("{0}-{1}-1", year, month));
int week = (int)dt.DayOfWeek;
int monthsDay = DateTime.DaysInMonth(int.Parse(year), int.Parse(month));
Console.WriteLine("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t");
for (int i = 0; i < week; i++)
{
    Console.Write("\t");
}
for (int i = 0; i < monthsDay; i++)
{
    Console.Write((i + 1) + "\t");
    if ((i + week + 1) % 7 == 0)
    {
        Console.WriteLine();
    }
}

Code analysis:

1. It is necessary to enter two information of year and month in the console.

string year = Console.ReadLine();

string month = Console.ReadLine();

2. It is necessary to calculate the day of the week on the first day of the current month based on the year and month.

Get a specific DateTime format timestamp:

DateTime dt = DateTime.Parse(string.Format("{0}-{1}-1", year, month));

Get the week corresponding to the 1st according to the specific DateTime.

int week = (int)dt.DayOfWeek;

Since it is an enumeration type, you can directly use strong casting to handle type changes. We can get the week of int type.

3. Calculate the maximum number of days in the current month based on the year and month.

int monthsDay = DateTime.DaysInMonth(int.Parse(year), int.Parse(month));

Using this method eliminates the need to calculate leap years. The relative efficiency will be much higher.

4. The traversal tab character \t is processed.

for (int i = 0; i < week; i++)
{     Console.Write("\t"); } The week we use here is the specific week of the 1st, and our week arrangement is as follows:


"Sunday\tMonday\tTuesday\tWednesday\tThursday\tFriday\tSaturday\t"

5. Change the line once a week.

for (int i = 0; i < monthsDay; i++)
{     Console.Write((i + 1) + "\t");     if ((i + week + 1) % 7 == 0)     {         Console.WriteLine( );     } } You can see that during the traversal process, the remainder 7 operation is performed on (i+week+1). If the result is 0, just wrap it directly.






Effect example:

Enter the year and month to get the ten thousand year month of the current month.

Actual Calendar:

This is from the actual calendar in February 2023, which is consistent with what we traversed. It is very important to calculate the corresponding week start.

 

Guess you like

Origin blog.csdn.net/feng8403000/article/details/130420975