温馨提示×

c#输出2023年的日历每一周为一行

c#
小亿
75
2023-12-21 13:39:44
栏目: 编程语言

以下是使用C#编写的代码,可以输出2023年的日历,每一周为一行:

using System;

class Program
{
    static void Main(string[] args)
    {
        // 设置要输出的年份
        int year = 2023;

        // 获取指定年份的第一天
        DateTime firstDay = new DateTime(year, 1, 1);

        // 获取指定年份的最后一天
        DateTime lastDay = new DateTime(year, 12, 31);

        // 当前日期,初始为第一天
        DateTime currentDate = firstDay;

        // 输出日历
        Console.WriteLine($"Calendar for {year}");

        while (currentDate <= lastDay)
        {
            // 输出当前日期所在周的一行
            for (int i = 0; i < 7; i++)
            {
                Console.Write(currentDate.Day.ToString().PadLeft(2) + " ");

                // 将日期增加一天
                currentDate = currentDate.AddDays(1);

                // 判断是否已经超过了指定年份的最后一天
                if (currentDate > lastDay)
                    break;
            }

            Console.WriteLine();
        }

        Console.ReadKey();
    }
}

这段代码首先设置要输出的年份为2023,然后使用DateTime类获取指定年份的第一天和最后一天。然后使用一个while循环来输出日历,循环中使用一个内嵌的for循环来输出每一周的一行,内部根据当前日期是否超过了指定年份的最后一天来决定是否退出循环。输出的日期使用PadLeft方法来对齐,确保两位数的日期都能正确显示。最后,使用Console.ReadKey方法等待用户按下任意键终止程序的执行。

0