Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a collection of months between two Dates?

Tags:

c#

.net

datetime

Below is my code. I am only getting the difference between two dates, but I want the name of that month which comes between the from and to dates.

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;
    }
}
like image 836
Sanjana Avatar asked Dec 09 '22 01:12

Sanjana


1 Answers

Based on your code you could substract the month difference from the "to" DateTime to get DateTime difference from your input.

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;
}

To get the name of the month just format the DateTime to "MMM".

var dts = GetMonthsBetween(DateTime.Today, DateTime.Today.AddMonths(5));
foreach (var dateTime in dts)
{
    Console.WriteLine(dateTime.ToString("MMM"));
}
like image 155
Andre Avatar answered Dec 11 '22 09:12

Andre