开发者

How to get month range from a given date range

For example if i give the startdate as 15开发者_JAVA技巧-mar-2009 and enddate as 15-mar-2010, I want to get the date range as given below,

Start Date      End Date

15-mar-2009     15-Apr-2009
15-apr-2009     15-may-2009    
...
15-mar-2010     15-apr-2010

Can anyone please help me in getting this.


You could try something like this, have an extension method (or non extension method) that returns an IEnumerable<DateTime>, you can iterate over this or use it in linq expression etc.

public static IEnumerable<DateTime> EnumerateUntilAfter(this DateTime startDate, DateTime endDate)
{
    if(endDate < startDate)
        throw new ArgumentOutOfRangeException("End date must be less than start date");
    return EnumerateUntilAfterImpl(startDate, endDate);
}

private static IEnumerable<DateTime> EnumerateUntilAfterImpl(DateTime startDate, DateTime endDate)
{
    while (startDate <= endDate)
    {
        yield return startDate;
        startDate = startDate.AddMonths(1);
    }
}

used like

public void DoTheThing(DateTime start, DateTime end)
{
    Console.WriteLine("StartDate\tEndDate");
    foreach (var date in start.EnumerateUntilAfter(end))
        Console.WriteLine("{0}\t{1}", date, date.AddMonths(1));
}

Gives you

StartDate   EndDate
15-Mar-2009 15-Apr-2009
15-Apr-2009 15-May-2009
15-May-2009 15-Jun-2009
15-Jun-2009 15-Jul-2009
15-Jul-2009 15-Aug-2009
15-Aug-2009 15-Sep-2009
15-Sep-2009 15-Oct-2009
15-Oct-2009 15-Nov-2009
15-Nov-2009 15-Dec-2009
15-Dec-2009 15-Jan-2010
15-Jan-2010 15-Feb-2010
15-Feb-2010 15-Mar-2010
15-Mar-2010 15-Apr-2010
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜