0

我需要在 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
4

1 回答 1

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

start它从到多年来end迭代,然后在每年的几个月中迭代,对边缘情况(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
        });
}
于 2013-05-07T23:27:13.880 回答