如何获得两个日期之间的月份集合?

San*_*ana 3 .net c# datetime

以下是我的代码.我只是得到两个日期之间的差异,但我想要那个月的名字来自于和来日期.

public static int GetMonthsBetween(DateTime from, DateTime to)
{
    if (from > to) return GetMonthsBetween(to, from);

    var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));

    if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
    {
        return monthDiff - 1;
    }
    else
    {
        return monthDiff;
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*dre 8

根据您的代码,您可以从"to"DateTime中减去月份差异,以从输入中获取DateTime差异.

public static List<DateTime> GetMonthsBetween(DateTime from, DateTime to)
{
    if (from > to) return GetMonthsBetween(to, from);

    var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));

    if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
    {
        monthDiff -= 1;
    }

    List<DateTime> results = new List<DateTime>();
    for (int i = monthDiff; i >= 1; i--)
    {
        results.Add(to.AddMonths(-i));
    }

    return results;
}
Run Code Online (Sandbox Code Playgroud)

要获取月份名称,只需将DateTime格式化为"MMM".

var dts = GetMonthsBetween(DateTime.Today, DateTime.Today.AddMonths(5));
foreach (var dateTime in dts)
{
    Console.WriteLine(dateTime.ToString("MMM"));
}
Run Code Online (Sandbox Code Playgroud)