在c#中有像python monthcalendar方法吗?

时间:2017-12-09 12:48:54

标签: c# python

我想将python代码转换为c#代码,在python代码中有一个名称为calendar.monthcalendar(year,month)的方法我不知道如何将其转换为c#代码。

  

monthcalendar()方法

     

monthrange()方法用于获取表示月份的矩阵   日历。每行代表一周;月外的日子a   以零为代表。除非设定,否则每周从星期一开始   setfirstweekday()。

1 个答案:

答案 0 :(得分:0)

static int[,] MonthCalendar(int year, int month, DayOfWeek firstWeekDay)
{
    int daysInMonth = DateTime.DaysInMonth(year, month);
    DayOfWeek first = new DateTime(year, month, 1).DayOfWeek;
    int left = ((int)first - (int)firstWeekDay + 7) % 7;
    int[,] arr = new int[7, (left + daysInMonth + 6) / 7];
    for (int i = 0; i < daysInMonth; i++)
    {
        int a = left + i;
        arr[a % 7, a / 7] = i + 1;
    }
    return arr;
}

static void Test(int year, int month, DayOfWeek firstWeekDay)
{
    string[] week = new string[]{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    Console.WriteLine(year + "-" + month);
    for (int i = (int)firstWeekDay; i < ((int)firstWeekDay + 7); i++)
    {
        Console.Write(" " + week[i % 7]);
    }
    Console.WriteLine();
    var arr = MonthCalendar(year, month, firstWeekDay);
    for (int y = 0; y < arr.GetLength(1); y++)
    {
        for (int x = 0; x < 7; x++)
        {
            Console.Write(arr[x, y].ToString().PadLeft(4));
        }
        Console.WriteLine();
    }
}

Test(2017, 12, DayOfWeek.Monday);输出:

2017-12
 Mon Tue Wed Thu Fri Sat Sun
   0   0   0   0   1   2   3
   4   5   6   7   8   9  10
  11  12  13  14  15  16  17
  18  19  20  21  22  23  24
  25  26  27  28  29  30  31