Monday, April 6, 2009

Get All Sundays in a Year

Following function will return all the Sundays in a specified Year.

/// /// This function will return all the dates of sundays in a Year
/// for example if you pass if year is 2009
/// it will return all the dates of sundays in the year in form of list
///

/// Year
/// List all dates of sundays in form of list string
public List getAllWeekDates(int Year)
{
List strDates = new List();
for (int month = 1; month <= 12; month++)
{
DateTime dt = new DateTime(Year, month, 1);
int firstSundayOfMonth = (int)dt.DayOfWeek;
if (firstSundayOfMonth != 0)
{
dt = dt.AddDays((6 - firstSundayOfMonth) + 1);
}
while (dt.Month == month)
{
strDates.Add(dt.ToString("dd/MMM/yyyy"));
dt = dt.AddDays(7);
}
}
return strDates;
}

Testing above function

List allSundays = getAllWeekDates(DateTime.Now.Year);
DropDownList1.DataSource = allSundays;
DropDownList1.DataBind();

Hope this helps

Tags: .NET, C# DateTime, All Sundays in a Year

No comments:

Post a Comment