日期范围在C#中拆分

时间:2013-05-07 23:06:29

标签: c#

我需要在C#

中按照给定的开始日期和结束日期按月分割日期

示例用户输入:

Start date : 5/20/2013
End date : 11/11/2013

我想将月份中的给定日期差异分开

输出:

StartDate    EndDate     NumberOfMonth
 5/20/2013   5/31/2013     .5
 6/1/2013    6/30/2013      1
 7/1/2013    7/31/2013      1
 8/1/2013    8/31/2013      1
 9/1/2013    9/30/2013      1
 10/1/2013   10/31/2013     1
 11/1/2013   11/11/2013    .5

1 个答案:

答案 0 :(得分:2)

我会抓住这个...你可以使用Linq一次生成所有日期范围。这不是最漂亮的查询,但它确实有效。

DateTime start = ...
DateTime end = ...
var cal = System.Globalization.CultureInfo.CurrentCulture.Calendar;

var range =
    from y in Enumerable.Range(start.Year, end.Year - start.Year + 1)
    let maxMonth = y < end.Year ? cal.GetMonthsInYear(y) : end.Month
    let minMonth = y > start.Year ? 1 : start.Month
    from m in Enumerable.Range(minMonth, maxMonth - minMonth + 1)
    let isStart = (y == start.Year && m == start.Month) 
    let isEnd = (y == end.Year && m == end.Month) 
    select new
    {
        StartDate = isStart ? start : new DateTime(y, m, 1),
        EndDate = isEnd ? end : new DateTime(y, m, cal.GetDaysInMonth(y, m)),
        NumberOfMonths = isStart || isEnd ? .5 : 1
    };

它从startend进行了多年的迭代,然后在每年的几个月内进行迭代,对边缘情况进行特殊处理(isStartisEnd) 。这个基本算法可以封装在这样的函数中:

public class DateTimeRange
{
    Date StartDate { get; set; }
    Date EndDate { get; set; }
    float NumberOfMonths { get; set; }
}

public static IEnumerable<DateTimeRange> SplitByMonths(DateTime start, 
                                                       DateTime end, 
                                                       Calendar cal)
{
    return (
        from y in Enumerable.Range(start.Year, end.Year - start.Year + 1)
        let maxMonth = y < end.Year ? cal.GetMonthsInYear(y) : end.Month
        let minMonth = y > start.Year ? 1 : start.Month
        from m in Enumerable.Range(minMonth, maxMonth - minMonth + 1)
        let isStart = (y == start.Year && m == start.Month) 
        let isEnd = (y == end.Year && m == end.Month) 
        select new DateTimeRange
        {
            StartDate = isStart ? start : new DateTime(y, m, 1),
            EndDate = isEnd ? end : new DateTime(y, m, cal.GetDaysInMonth(y, m)),
            NumberOfMonths = isStart || isEnd ? .5 : 1
        });
}