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

   2025-02-13 7150
核心提示:以下是使用C#编写的代码,可以输出2023年的日历,每一周为一行:using System;class Program{static void Main(string[] args){/

以下是使用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方法等待用户按下任意键终止程序的执行。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言