Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Splitting Dates of Different Months in Asp.Net

0.00/5 (No votes)
27 Feb 2014 1  
Splitting dates of different months in Asp.Net

Introduction 

Sometimes there may be necessary of splitting days in a particular month. As it is easy if we know the month of the date. What if the selection of dates are of different months? then look over my trick.

Background

If you want require inserting(records) dates of particular month to database or need to show, splitting of dates by month is useful.

Using the code

Here for viewers convenient i am binding the separated dates to GridView with number of days
<asp:GridView ID="gvDates" runat="server" AutoGenerateColumns="false">
  <Columns>
      <asp:BoundField DataField="startDate" HeaderText="Start Date" dataformatstring="{0:dd/MM/yyyy}"/>
      <asp:BoundField DataField="endDate" HeaderText="End Date" dataformatstring="{0:dd/MM/yyyy}" />
      <asp:BoundField DataField="days" HeaderText="Days" />
  </Columns>
</asp:GridView>     

For List, I am defining class:

public class splitDates
{
   public DateTime startDate { get; set; }
   public DateTime endDate { get; set; }
   public double days { get; set; }
}

Here on button click, I am splitting the dates:

protected void btnSplit_Click(object sender, EventArgs e)
{
    DateTime dt1, dt2, monthStartDate, monthEndDate;
    List<splitDates> listDates = new List<splitDates>();
    dt1 = Convert.ToDateTime(txtFromDate.Text);
    dt2 = Convert.ToDateTime(txtToDate.Text);
    monthStartDate = dt1.AddDays(-1 * dt1.Day + 1);
    monthEndDate = monthStartDate.AddMonths(1).AddDays(-1);
    
    if (monthEndDate < dt2)
    {
        while (monthEndDate < dt2)
        {
            listDates.Add(new splitDates { startDate = dt1, endDate = monthEndDate, days = ((monthEndDate - dt1).TotalDays) + 1 });
            monthStartDate = monthEndDate.AddDays(1);
            dt1 = monthStartDate;
            monthEndDate = monthStartDate.AddMonths(1).AddDays(-1);
        }

        listDates.Add(new splitDates { startDate = monthStartDate, endDate = dt2, days = ((dt2 - monthStartDate).TotalDays) + 1 });
    }
    else
    {
        listDates.Add(new splitDates { startDate = dt1, endDate = dt2, days = (dt2 - dt1).Days + 1 });
    }

    gvDates.DataSource = listDates;
    gvDates.DataBind();
}
   

Resources  

  1. www.stackoverflow.com
  2. www.nullskull.com

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here