0

Possible Duplicate:
Calculate date from week number

I have a week number and i am trying to create function to return first and last day of this week.

For examle for week #29 first day will be 2012-07-16 and last will be 2012-07-22.

Community
  • 1
  • 1

1 Answers1

2

How about this:

int year = 2012;
int weekNumber = 29;

var thursdayInWeek01 = Enumerable.Range(1, 7).Select(i => new DateTime(year, 1, i))
  .First(d => d.DayOfWeek == DayOfWeek.Thursday);
var thursdayInCorrectWeek = thursdayInWeek01.AddDays((weekNumber - 1) * 7);

var firstDay = thursdayInCorrectWeek.AddDays(-3);
var lastDay = thursdayInCorrectWeek.AddDays(3);

It's ISO style week numbers.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • I think this could be off in edge cases. If the Jan 1 is on a Fri., do you consider that Fri-Sat to be one week, or not a week at all, or what? In your code, you're pretending it's not even a week. (I think) – Servy Aug 09 '12 at 16:25
  • @Servy No, it's [ISO week](http://en.wikipedia.org/wiki/ISO_week_date) numbers. If Jan 1st is a Friday, that week is week 53 of the preceding year (preceding year has 53 Thursdays). In that case week 1 will start on Jan 4th. Any week starts on a Monday and ends on a Sunday, even weeks spanning over two calendar years. Above algorithm is exact even in edge cases. ISO week numbers are commonly used where I live (Denmark). – Jeppe Stig Nielsen Aug 09 '12 at 21:19