C# .NET - Split the date for the given date range

Asked By MySpider DotNet on 07-May-13 07:22 PM

I need to split the date in month wise for the given start date and end date in C#

Example

- User Input:

Start date : 5/20/2013

End date : 11/11/2013

I want to splite the give date difference in month

- OutPut:

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

Robbe Morris replied to MySpider DotNet on 07-May-13 09:24 PM
Look up the TimeSpan class.
Sandeep Mittal replied to MySpider DotNet on 14-May-13 01:55 AM
protected void Page_Load(object sender, EventArgs e)
{
  DateTime dt1, dt2, monthStartDate, monthEndDate;
  List<clsDates> listDates = new List<clsDates>();
  dt1 = Convert.ToDateTime("20/05/2013");
  dt2 = Convert.ToDateTime("11/11/2013");
  monthStartDate = dt1.AddDays(-1 * dt1.Day + 1);
  monthEndDate = monthStartDate.AddMonths(1).AddDays(-1);         
  while (monthEndDate < dt2)
  {
    listDates.Add(new clsDates { startDate = dt1, endDate = monthEndDate, days = (monthEndDate - dt1).TotalDays / (monthEndDate - monthStartDate).TotalDays });
    monthStartDate = monthEndDate.AddDays(1);
    dt1 = monthStartDate;
    monthEndDate = monthStartDate.AddMonths(1).AddDays(-1);
  }
  listDates.Add(new clsDates { startDate = monthStartDate, endDate = dt2, days =(dt2 -monthStartDate).TotalDays / (monthEndDate - monthStartDate).TotalDays });     
  gv.DataSource = listDates;
  gv.DataBind();
}
 
public class clsDates
{
  public DateTime startDate { get; set; }
  public DateTime endDate { get; set; }
  public double days { get; set; }
}