Sanjana
Sanjana

Reputation: 43

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

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

Upvotes: 4

Views: 6879

Answers (3)

Andre
Andre

Reputation: 1238

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

Upvotes: 10

Hans Kesting
Hans Kesting

Reputation: 39358

If you want the names of all months between two dates, use something like this:

var d1 = new DateTime(2015,6,1);
var d2 = new DateTime(2015,9,1);

var monthlist = new List<string>();
string format = d1.Year == d2.Year ? "MMMM" : "MMMM yyyy";

for (var d = d1; d <= d2; d = d.AddMonths(1))
{
    monthlist.Add(d.ToString(format));
}

The full list is now in monthlist - you will want to return that from your method.

Upvotes: 3

Aron_dc
Aron_dc

Reputation: 863

Assuming you're using Java and JodaTime there are several flaws in your code.

  1. You cant use from > to to evaluate if a date is after an other. Use from.isAfter(to) instead.
  2. JodaTime already supplies a method to calculate the amount of whole months between two given Dates Months.monthsBetween(start,end).
  3. With the calculated month difference you can instantiate a new DateTime object that holds a date in your desired month and output its name via yourNewDateTimeObject.month().getAsText().

edit: Just found out you're using C# so ignore my text above this. Below here I will try to answer your question in C#.

  1. Why dont you just subtract the from from the to date and obtain your difference?

  2. The resulting TimeSpan can be used to determine the amount of whole months between your two given dates.

  3. To obtain the resulting month name you could use yourDateTime.ToString("MMMM");

Upvotes: 1

Related Questions