Thursday, July 31, 2014

How to find no of Sundays in a month in ASP.NET C#

Today I was asked how to find no of Sundays in a month by one of my colleague. To make him happy I found the code and now sharing this with all of you to make you all happy.

A simple code to find the no of Sundays in a months using List.


protected void Page_Load(object sender, EventArgs e)
{
      List<DateTime> dates = new List<DateTime>();
      int year = 2013;
      int month = 1;

      DayOfWeek day = DayOfWeek.Sunday;
      System.Globalization.CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
      for (int i = 1; i <= currentCulture.Calendar.GetDaysInMonth(year, month); i++)
      {
            DateTime d = new DateTime(year, month, i);
            if (d.DayOfWeek == day)
            {
                dates.Add(d);
            }
      }

      Response.Write(dates.Count.ToString());
      GridView1.DataSource = dates;
      GridView1.DataBind();
}

And in the ASPX page coding ...


<head runat="server">
    <title>Show Sundays in a month using ASP.NET C#</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    </div>
    </form>
</body>

Now the output :



Test the code and before that download the full source code here.

0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews