📌  相关文章
📜  获取两个日期之间的月份和年份列表c#代码示例

📅  最后修改于: 2022-03-11 14:49:13.954000             🧑  作者: Mango

代码示例2
public static IEnumerable<(string Month, int Year)> MonthsBetween(
        DateTime startDate,
        DateTime endDate)
{
    DateTime iterator;
    DateTime limit;

    if (endDate > startDate)
    {
        iterator = new DateTime(startDate.Year, startDate.Month, 1);
        limit = endDate;
    }
    else
    {
        iterator = new DateTime(endDate.Year, endDate.Month, 1);
        limit = startDate;
    }

    var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
    while (iterator <= limit)
    {
        yield return (
            dateTimeFormat.GetMonthName(iterator.Month), 
            iterator.Year
        );

       iterator = iterator.AddMonths(1);
    }
}