C#获取一个月的星期
时间: 2023-10-19 12:11:06 浏览: 88
你可以使用 DateTime 类和 DayOfWeek 枚举来获取一个月的星期。以下是一个示例代码:
```csharp
using System;
class Program {
static void Main(string[] args) {
int year = 2021;
int month = 10;
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DayOfWeek dayOfWeek = firstDayOfMonth.DayOfWeek;
int daysInMonth = DateTime.DaysInMonth(year, month);
Console.WriteLine("First day of month: {0}", firstDayOfMonth.ToShortDateString());
Console.WriteLine("Day of week: {0}", dayOfWeek);
Console.WriteLine();
int weekCount = 1;
for (int i = 1; i <= daysInMonth; i++) {
DateTime date = new DateTime(year, month, i);
if (date.DayOfWeek == DayOfWeek.Sunday) {
Console.WriteLine("Week {0}: {1}", weekCount, date.ToShortDateString());
weekCount++;
}
}
}
}
```
在上面的示例中,我们首先获取指定年份和月份的第一天的 DayOfWeek 枚举值,然后计算该月的天数。接下来,我们遍历该月的每一天,并在日期是星期日时输出该周的第一天。这样,我们就可以获取一个月的所有星期。
阅读全文