posted 9/5/2010 by Vijendra Shakya
Here I have discussed about how to get all the dates of any Dayofweek in a year. Below is the stpes to caluclate all Dayofweek in a year. 1. Initialize a Collection for adding all Sundays in that.
Collection<DateTime> listOfSundays = new Collection<DateTime>()
2. For that first we get the start date of the year as follows:
DateTime startDate = new DateTime(year, 1, 1);
3. Now we check that startDate’s Day is equal to day of week which you want to find out or not.
if (DayOfWeek.Sunday == startDate.DayOfWeek)
1.If this condition is true i.s DayOfWeek is the dayofweek which you want to findout then we add the startDate to the collection.
listOfSundays.Add(startDate)
Add 7 days in the startDate.
startDate = startDate.AddDays(7);
2. If above if condition is not true i.e DayofWeek is not dayofweek which you want then we add the numberof days in the startdate which we get the start date of the dayofweek which you want .
int dayAdd = (int)dayOfWeek - (int)startDate.DayOfWeek; if ((int)startDate.DayOfWeek > (int)dayOfWeek) { dayAdd = 7 + dayAdd; } startDate = startDate.AddDays(dayAdd);
Step 3 need to iterate untill we did not get next year date, so put step 3 in a while loop like
while (year == startDate.Month) { /*use step 3 here*/ }
Finally mearge all the steps the final code snippet will be:
static Collection<DateTime> ListOfSundays(int year, DayOfWeek dayOfWeek) { var listOfSundays = new Collection<DateTime>(); var startDate = new DateTime(year, 1, 1); while (year == startDate.Year) { if (DayOfWeek.Sunday == startDate.DayOfWeek) { listOfSundays.Add(startDate); startDate = startDate.AddDays(7); } else { int dayAdd = (int)dayOfWeek - (int)startDate.DayOfWeek; if ((int)startDate.DayOfWeek > (int)dayOfWeek) { dayAdd = 7 + dayAdd; } startDate = startDate.AddDays(dayAdd); } } return listOfSundays; }
Now we can use this this function like below:
foreach (var sunday in ListOfSundays(2010,DayOfWeek.Sunday)) { Response.Write(sunday.Date.ToString("dd MMMM,yyyy") + "<br/>"); }
OUTPUT: 03,January,2010 10,January,2010 17,January,2010 24,January,2010 31,January,2010 ................. 05,December,2010 12,December,2010 9,December,2010 26,December,2010 You can also do this via using the yield keyword like below:
static IEnumerable<DateTime> ListOfSundays(int year, DayOfWeek dayOfWeek) { var startDate = new DateTime(year, 1, 1); while (year == startDate.Year) { if (dayOfWeek == startDate.DayOfWeek) { yield return startDate; startDate = startDate.AddDays(7); } else { int dayAdd = (int)dayOfWeek - (int)startDate.DayOfWeek; if ((int)startDate.DayOfWeek > (int)dayOfWeek) { dayAdd = 7 + dayAdd; } startDate = startDate.AddDays(dayAdd); } } }
Thanks Vijendra Singh
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18