0

I am trying to get all the weekdays of the selected Month along with the day like Monday or Tuesday, etc?? How is it possible? is there an inbuilt function that i do not know?

This is in C# 2.0, asp.net using VS 2005

challengeAccepted
  • 7,106
  • 20
  • 74
  • 105

2 Answers2

5

I make no guarantees about leap years, daylight savings jumps, special days, Shanghai 1927, etc.

public List<DateTime> getWeekdatesandDates(int Month, int Year)
{
    List<DateTime> weekdays = new List<DateTime>();

    DateTime firstOfMonth = new DateTime(Year, Month, 1);

    DateTime currentDay = firstOfMonth;
    while (firstOfMonth.Month == currentDay.Month)
    {
        DayOfWeek dayOfWeek = currentDay.DayOfWeek;
        if (dayOfWeek != DayOfWeek.Saturday && dayOfWeek != DayOfWeek.Sunday)
            weekdays.Add(currentDay);

        currentDay = currentDay.AddDays(1);
    }

    return weekdays;
}

The resultant DateTime objects have a DayOfWeek property which you can check to see if it's Monday through Friday.

Community
  • 1
  • 1
Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93
1

This should work

private List<DateTime> getWeekDayDates(int month, int year)
{
    List<DateTime> weekdays = new List<DateTime>();
    DateTime basedt = new DateTime(year, month, 1);
    while ((basedt.Month == month) && (basedt.Year == year))
    {
        if (basedt.DayOfWeek == (DayOfWeek.Monday | DayOfWeek.Tuesday | DayOfWeek.Wednesday | DayOfWeek.Thursday | DayOfWeek.Friday))
        {
            weekdays.Add(new DateTime(basedt.Year, basedt.Month, basedt.Day));
        }
        basedt = basedt.AddDays(1);
    }
    return weekdays;
}

Then you can get whatever info out of each DateTime you need.

Wanabrutbeer
  • 676
  • 6
  • 11
  • That weekday check won't work that way. I suspect you want: `if ((basedt.DayOfWeek & (DayOfWeek.Monday | DayOfWeek.Tuesday | DayOfWeek.Wednesday | DayOfWeek.Thursday | DayOfWeek.Friday)) != 0)` or some equivalent. EDIT: And the year check I think is superfluous (I can think of no conditions in which the year would change but not the month) – Chris Sinclair Oct 15 '12 at 21:02
  • 1
    I may have the dayofweek syntax wrong, i dont write clauses like that often, and i thought of the same thing on the year check, but figured why not. – Wanabrutbeer Oct 15 '12 at 23:52