SaraCh
SaraCh

Reputation: 33

Calculate the Months between two months

In my project, i am saving all the dates in the form of string like say "07/26/2013" in the database.But now, there came a situation where i need to retrieve two dates and then check the months between those two start and end month.

Eg: If the start date is 01/01/2013 and the end month is 05/01/2013, i should get the answer like {"Jan", "Feb", "Mar", "Apr", "May"} or {"01", "02", "03", "04", "05"}. I have tried collections but receive an error index out of range. Any help is appreciated!

Thanks! Sara.

Upvotes: 0

Views: 219

Answers (2)

Deeko
Deeko

Reputation: 1539

I imagine there is a simpler way to do this with Linq, but a simple loop would do the job:

DateTime start = DateTime.Parse(startString);
DateTime end = DateTime.Parse(endString);
List<string> months = new List<string>();
while (start.Month <= end.Month)
{
    months.Add(start.ToString("MMM"));
    start = start.AddMonths(1);
}
string output = string.Join(",", months.ToArray());

See this MSDN page for info on formatting the month output via ToString(): http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx

Upvotes: 1

Ivan I
Ivan I

Reputation: 9990

This takes one of your dates and converts it to the proper string. Getting month of it is not a problem, and I guess you are mistaking because of conflict in which dates are converted to and from string on your computer.

        string date1 = "05/01/2013";
        DateTime date = Convert.ToDateTime(date1, System.Globalization.CultureInfo.InvariantCulture);
        MessageBox.Show(date.ToString());

Upvotes: 0

Related Questions