Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to know when given start and end dates, how can the months and year(s) between the two dates be retrieved.

Eg: Start Date: '1/1/2011'(mm/dd/yyyy) and End date :'11/30/2011'. The months and year to be retrieved are January,2011; February,2011; March,2011; and so on till November,2011

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
417 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here we go

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

And obviously you call it like this

var startDate = DateTime.ParseExact("01/01/2011", "MM/dd/yyyy");
var endDate = DateTime.ParseExact("11/30/2011", "MM/dd/yyyy");

var months = MonthsBetween(startDate, endDate);

The results should be something like

{
    {  "January", 2011  },
    {  "February", 2011  },
    {  "March", 2011  },
    {  "April", 2011  },
    {  "May", 2011  },
    {  "June", 2011  },
    {  "July", 2011  },
    {  "August", 2011  },
    {  "September", 2011  },
    {  "October", 2011  },
    {  "November", 2011  },
}

The month names being dependent on your culture which, I think, is exactly what you asked for, right?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...