Get Date Range by week number c#
Solution 1
Note
I appear to have missed bug. The current code have been updated as of 2012-01-30 to account for this fact and we now derive the
daysOffset
based on Tuesday which according to Mikael Svenson appears to solve the problem.
These ISO8601 week date calculations are a bit wonky, but this is how you do it:
DateTime jan1 = new DateTime(yyyy, 1, 1);
int daysOffset = DayOfWeek.Tuesday - jan1.DayOfWeek;
DateTime firstMonday = jan1.AddDays(daysOffset);
var cal = CultureInfo.CurrentCulture.Calendar;
int firstWeek = cal.GetWeekOfYear(jan1, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
var weekNum = ww;
if (firstWeek <= 1)
{
weekNum -= 1;
}
var result = firstMonday.AddDays(weekNum * 7 + d - 1);
return result;
Basically calculate a reference point, then add days, the hard stuff has to do with the fact that week 53 can sometimes occur in January and week 1 can sometimes occur in December. You need to adjust for that and this is one way to do that.
The above code calculates the date off a year (yyyy) and week number (ww) and day of week (d).
Solution 2
- Find out which day of the week was the first January of the year (e.g. in 2011 it was Saturday)
- Add the necessary count of days to become the next monday (2 days)
- From this day on, add (Number of weeks - 1) * 7 days to get the first day of the week you are interested in -Display this day plus the next days to get the whole week
Wesley
Updated on June 13, 2022Comments
-
Wesley almost 2 years
Possible Duplicate:
In .net, knowing the week number how can I get the weekdays date?Hello,
I've got a question for ya'll. How do i get the date range of a given week number.
For example: If I enter week 12 the output should be:
21-03-2011 22-03-2011 23-03-2011 24-03-2011 25-03-2011 26-03-2011 27-03-2011
I really hope you guys can help me out, i just cant find the awnser anywhere!
Thanks in advance.
-
Martin Milan about 13 yearsWon't downvote - but John's solution below is correct. This is all laid out in ISO stuff...
-
John Leidegren about 13 yearsYes, this is too simplistic and occasionally computes the wrong date.
-
Mikael Svenson about 12 yearsIf I enter yyyy=2012, ww=1 and d=Monday(1), your code returns Jan 9th and not Jan 2nd which would be correct.
-
Mikael Svenson about 12 yearsSee my answer here: stackoverflow.com/a/9064954/153390
-
John Leidegren about 12 yearsThat's unfortunate, I do remember reworking this code and creating a lot of test but this is older and obviously not right, your small change however seem to work and I don't have the ability to test this more thoroughly, so I'm gonna believe that you did that yourself and correct my own answer ;)
-
Mikael Svenson about 12 yearsTested it for every day from 1900-1-1 to 3000-12-31 :)