-6

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

Willdune
  • 13
  • 3
  • 2
    Do you actually only send the day of the month without specifying the month and year? – Martheen May 08 '21 at 12:59
  • Where does your week start? Sunday? Monday? – Martheen May 08 '21 at 12:59
  • Yes, you're correct. didn't thought that, look the edit i've made, imagine i seend the simple date format. And week starts on monay. – Willdune May 08 '21 at 13:02
  • Did you consider that e.g. Monday might be in a different Month than the date given? – Klaus Gütter May 08 '21 at 13:04
  • 1
    What if I send `1` or `31`: shall I return days of the *previuos* (*next*) month? I.e. `int[] {29, 30, 1, 2, 3}` – Dmitry Bychenko May 08 '21 at 13:04
  • Didn't thought all that, sry, instead of returning just the day of the month, consider returning a simpledate format corresponding to every day of the week: (17/05/2021, 18/05/2021, 19/05/2021, 20/05/2021, 21/05/2021) – Willdune May 08 '21 at 13:07
  • 1
    Every datetime has a property called [DayOfWeek](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.dayofweek?view=net-5.0) that you can compare against [the DayOfWeek enum](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.dayofweek?view=net-5.0). Now a DateTime can be changed to the prior date with _AddDays(-1)_ So just loop backwards till you find the Monday enum, at this point you can get easily the next five days with AddDays(1). Come on let's try it. You can do it – Steve May 08 '21 at 13:11
  • Good solution! Thank you so much, i'll try it! – Willdune May 08 '21 at 13:15

1 Answers1

1
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;
}
Willdune
  • 13
  • 3