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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With