Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Date Range by week number c# [duplicate]

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.

like image 889
Wesley Avatar asked Mar 21 '11 12:03

Wesley


2 Answers

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).

like image 55
John Leidegren Avatar answered Oct 23 '22 14:10

John Leidegren


  • 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
like image 24
Tomas Walek Avatar answered Oct 23 '22 12:10

Tomas Walek