How to create a dll in dotnet

To get something you never had, you have to do something you never did-Bimal Patel

Thursday, November 18, 2010

Get Total Number Of Sundays in a Month in c#

The function  below gives the total number of sundays .
Input parameters for this function are month and year.


private string GetNumberOfSundaysiInMonth(int  Month, int Year)
    {
        DateTime StartDate = Convert.ToDateTime(Month.ToString() + "/01/" + Year.ToString());
      int  iDays = DateTime.DaysInMonth(Year, Month);
        DateTime EndDate = StartDate.AddDays(iDays - 1);
        int  Count = 0;
      int  SundayCount = 0;
        while (StartDate.DayOfWeek != DayOfWeek.Sunday)
        {
            StartDate = StartDate.AddDays(1);
        }
        SundayCount = 1;
        StartDate = StartDate.AddDays(7);
        while (StartDate <= EndDate)
        {
            SundayCount += 1; StartDate = StartDate.AddDays(7);
        }
        return SundayCount.ToString();
    }

Now lets us  test the function

1)Take a calendar and drag on to your page.

2)Now write the below code in selectionchanged event of the calendar

  protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        String _sun = GetNumberOfSundays(Calendar1.SelectedDate.Month, Calendar1.SelectedDate.Year);
        Response.Write(_sun);
    }

 Now it  prints the sundays in the page


Small Tip
At few times we may need to change the colour of all the dates with sundays/saturdays or specific days

then here is the code , we need to handle the day render event of the calendar,

 protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.IsWeekend)
            e.Cell.ForeColor = System.Drawing.Color.Red;
    }



So apply this code and test at your end .Happy coding



No comments:

Post a Comment