Search code examples
c#calendardayofweek

Get days of a week, by a day of the month


I've been looking arround on stackoverflow, and i couldn't find how can i do the following problem on C#. I need a method that i'll send a int (day of the month), it always return de days of the month from monday to friday of the week the day belong.

For example: Today is 8, and i need that the method returns an array with the following numbers (3, 4, 5, 6, 7).

Or imagine, that even if its 8, i send to this method 19, it returns (17, 18, 19, 20, 21) Corresponding 17 to monday, 18 to tuesday....

I don't have any code, because i don't know how to do it. Hope you can help me!

Thanks a lot!

Edit: instead of just sending the day, imagine i send a simple date format 08/05/2021


Solution

  • private DateTime[] weekByDay(DateTime date)
    {
      DateTime[] week = new DateTime[5];
      while (date.DayOfWeek != DayOfWeek.Monday) //while day is not monday
      {
        date = date.AddDays(-1); //substract 1 day to date
      }
      week[0] = date; //add the current day (monday), to the array
      for (int i = 1; i < 5; i++) //add the next day till Friday
      {
       date = date.AddDays(1);
       week[i] = date;
      }
      Console.WriteLine("MONDAY was " + week[0]);
      Console.WriteLine("TUESDAY was " + week[1]);
      Console.WriteLine("WEDNESDAY was " + week[2]);
      Console.WriteLine("THURSDAY was " + week[3]);
      Console.WriteLine("FRIDAY was " + week[4]);
      return week;
    }