如何获得两个日期之间的月份和剩余天数(即开始日期和结束日期)

时间:2016-07-13 15:57:33

标签: c# linq

我试图破解逻辑,但直到现在都没有运气。需要您的支持才能解决问题。我需要计算开始日期和结束日期之间一个月内发生的天数。

详细说明,以下是输入结构:

  

ID |开始日期|结束日期

     

1 | 15-Jan-16 | 15-Feb-16

     

2 | 23-Jan-16 | 15-Mar-16

从上面的表格中,应用程序计算特定月份的天数。例如对于ID = 1,Jan有16天,2月有14天。表单将转换为以下输出:

  

ID |月|天

     

1 | Jan | 16

     

1 |二月| 14

     

2 | Jan | 8

     

2 |二月| 29

     

2 | Mar | 13

有什么方法可以做到吗?

4 个答案:

答案 0 :(得分:1)

查看TimeSpan

您可以使用它来表示以天,小时甚至分钟为单位的时间间隔。

答案 1 :(得分:1)

我相信您在问题中提供的结果不正确,但您可以这样做:

var obj = new[] {
    new { ID=1, StartDate=new DateTime(2016,1,15), EndDate=new DateTime(2016,2,15) },
    new { ID=2, StartDate=new DateTime(2016,1,23), EndDate=new DateTime(2016,3,15) }
};

var result=obj.SelectMany(x=>
    Enumerable.Range(0,int.MaxValue)
        .Select(m=>new DateTime(x.StartDate.Year,x.StartDate.Month,1).AddMonths(m))
        .TakeWhile(m=>m<x.EndDate)
        .Select(m=>new {
            x.ID,
            //m.Year,
            Month=m.ToString("MMM"),
            Days=(x.EndDate.Year==m.Year && x.EndDate.Month==m.Month?x.EndDate.Day:DateTime.DaysInMonth(m.Year,m.Month))
            -(x.StartDate.Year==m.Year && x.StartDate.Month==m.Month?x.StartDate.Day:0)
        })
);

enter image description here

答案 2 :(得分:0)

您需要拆分字段,然后解析日期,例如:

DateTime.ParseExact(text, 
   "dd-MMM-yy", 
   CultureInfo.InvariantCulture,
   DateTimeStyles.AllowWhiteSpaces);

然后从初始日期循环到最后一个日期。我建议使用开始日期的第一天到循环的最后一个日期的第一天(否则如果第一个月的日期大于上个月的那天,则无法执行上个月)。要增加,请使用AddMonth(1)方法。您可以使用DateTime.DaysInMonth(year,month)获取每月的天数。

第一个月,从该月的日期中减去第一个日期的日期。

上个月,从最后一天的日期减去1。

其他月份,只需选择月中的日子。

答案 3 :(得分:0)

以下是使用小辅助方法执行此操作的一种方法:

var data = ranges
    .SelectMany(r => GetMonthlyDates(r.From, r.To)
        .Select(m => new
        {
            r.ID,
            MonthName = m.ToString("MMM"),
            Days = m.Year == r.From.Year && m.Month == r.From.Month
                ? DateTime.DaysInMonth(m.Year, m.Month) - m.Day
                : (m.Year == r.To.Year && m.Month == r.To.Month ? r.To.Day : DateTime.DaysInMonth(m.Year, m.Month))
        }));

private static IEnumerable<DateTime> GetMonthlyDates(DateTime from, DateTime to)
{
    for (DateTime current = from; current.Year < to.Year || current.Month <= to.Month; current = current.AddMonths(1))
        yield return current;
}

这给了我:

1 | Jan | 16
1 | Feb | 15
2 | Jan | 8
2 | Feb | 29
2 | Mar | 15
相关问题