Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

c# - List the months between two dates

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

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

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...