前言
我们使用了一个
List<string>
来存储每个年和月的字符串,然后使用for
循环遍历日期范围内的每个月份,将其转换为yyyy-MM
格式的字符串,并将其添加到列表中。最后,我们使用
ToArray()
方法将列表转换为字符串数组,并将其存储在yearMonthArray
变量中。
示例
DateTime startDate = new DateTime(2023, 1, 1);
DateTime endDate = new DateTime(2023, 12, 31);
List<string> yearMonths = new List<string>();
for (DateTime date = startDate; date <= endDate; date = date.AddMonths(1))
{
string yearMonth = date.ToString("yyyy-MM");
yearMonths.Add(yearMonth);
}
string[] yearMonthArray = yearMonths.ToArray();