c# 如何取两个日期之间每个月份集合
时间: 2024-03-10 21:43:33 浏览: 85
你可以使用 C# 中的 `DateTime` 类型和 `AddMonths` 方法来计算两个日期之间的每个月份。具体步骤如下:
1. 将开始日期和结束日期转换为 `DateTime` 类型。
```csharp
DateTime startDate = DateTime.Parse("2022-01-01");
DateTime endDate = DateTime.Parse("2022-06-30");
```
2. 循环遍历两个日期之间的每个月份,并将其添加到集合中。
```csharp
List<DateTime> months = new List<DateTime>();
DateTime tempDate = new DateTime(startDate.Year, startDate.Month, 1);
while (tempDate <= endDate)
{
months.Add(tempDate);
tempDate = tempDate.AddMonths(1);
}
```
3. `months` 列表中存储了两个日期之间的每个月份。
完整代码如下:
```csharp
DateTime startDate = DateTime.Parse("2022-01-01");
DateTime endDate = DateTime.Parse("2022-06-30");
List<DateTime> months = new List<DateTime>();
DateTime tempDate = new DateTime(startDate.Year, startDate.Month, 1);
while (tempDate <= endDate)
{
months.Add(tempDate);
tempDate = tempDate.AddMonths(1);
}
foreach (DateTime month in months)
{
Console.WriteLine(month.ToString("yyyy-MM"));
}
```
阅读全文
相关推荐

















