Wednesday, June 15, 2011

How to get date for every sunday in a month using asp.net with c#

In this programming tutorial you will learn how to get the date for every sunday in a month using asp.net with c#. There are multiple methods to achieve our goal. Let`s have a look over them.

How to get date for every sunday in a month in asp.net using c#

Method 1

using System.Globalization;//Donot forget to declare this namespace
 protected void Page_Load(object sender, EventArgs e)
    {
 DateTime currentDateTime=System.DateTime.Now;
        int year=currentDateTime.Year;
        int months=currentDateTime.Month;
        GetDatesOfSundays(year, months, DayOfWeek.Sunday);
    }
    protected void GetDatesOfSundays(int year, int month, DayOfWeek dayName)
    {
        CultureInfo ci = new CultureInfo("en-US");
        for (int i = 1; i <= ci.Calendar.GetDaysInMonth(year, month); i++)
        {
            if (new DateTime(year, month, i).DayOfWeek == dayName)
                Response.Write(i.ToString() + ",");
        }
    }

Output
1,8,15,22,29

 


Method 2

protected void Page_Load(object sender, EventArgs e)
    {
     Response.Write(GetDatesOfSundays(System.DateTime.Now));
    }
private string GetDatesOfSundays(DateTime DatMonth)
    {
        string sReturn = "";
        int iDayOffset = DatMonth.Day - 1;
        DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
        DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
        while (DatMonth < DatMonth2)
        {
            if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
            {
                if (sReturn.Length > 0) sReturn += ",";
                sReturn += DatMonth.ToShortDateString();
            }
            DatMonth = DatMonth.AddDays(1.0);
        }
        return sReturn;
    } 

Output
5/1/2011,5/8/2011,5/15/2011,5/22/2011,5/29/2011


So these are the methods to find the sundays in a month using asp.net with c#.

0 comments:

Post a Comment