st4ticv0id
st4ticv0id

Reputation: 39

C# - Get the first day and last day of the week knowing the week number, month number and year

so the problem is this: I managed to get the number of weeks that make up a month (for example: May 2022 is made up of 6 weeks counting from day 1 to day 31 without exception). So having the number of weeks that make up a month I need to know, knowing also the number of the month and the year, which will be the first and last day of the selected week.

I tried to do some research but I only find solutions that use the Calendar.GetWeekOfYear method but, as I said before, I have the week number for the single month not the total for the year.

I hope you can help me. Thanks in advance.

Upvotes: 0

Views: 457

Answers (1)

GuyVdN
GuyVdN

Reputation: 692

If I understood correctly it should look something like this

var week = 2;
var month = 5;
var year = 2022;

var firstDayOfMonth = new DateTime(year, month, 1);
var dayOfWeek = firstDayOfMonth.DayOfWeek;
var diffToMonday = (7 + (dayOfWeek - DayOfWeek.Monday)) % 7;
var firstMonday = firstDayOfMonth.AddDays(-diffToMonday);

var requestedMonday = firstMonday.AddDays(7 * (week - 1));
var requestedSunday = firstMonday.AddDays(7 * week - 1);

Upvotes: 1

Related Questions