9

I want to create a function in C# which for a week number will return me the days, in that week.

For instance for week number 40, how can I get the days: 4/10, 5/10, 6/10, 7/10, 8/10, 9/10, 10/10.

Thank you in advance!

  • possible duplicate of [Calculate date from week number](http://stackoverflow.com/questions/662379/calculate-date-from-week-number) –  Jun 06 '13 at 15:34

3 Answers3

10

I think this should do what you want:

    public static DateTime[] WeekDays(int Year, int WeekNumber)
    {
        DateTime start = new DateTime(Year, 1, 1).AddDays(7 * WeekNumber);
        start = start.AddDays(-((int)start.DayOfWeek));
        return Enumerable.Range(0, 7).Select(num => start.AddDays(num)).ToArray();
    }

Although I treat Sunday as first day of week, if you want Monday as first day change range from (0,7) to (1,7).

If you want to conform the ISO standard, I think this should work:

    public static DateTime[] WeekDays(int Year, int WeekNumber)
    {
        DateTime start = new DateTime(Year, 1, 4);
        start = start.AddDays(-((int)start.DayOfWeek));
        start = start.AddDays(7 * (WeekNumber - 1));
        return Enumerable.Range(0, 7).Select(num => start.AddDays(num)).ToArray();
    }
JDunkerley
  • 12,355
  • 5
  • 41
  • 45
  • 1
    That basically depends on where in the world you are, because in Europe Week 1 is the first week with 4 days, whereas in US it is the week with 1/1 (http://en.wikipedia.org/wiki/Seven-day_week#Week_numbering) - so code is correct except the "base" might need to be adjusted. – veggerby Oct 04 '10 at 10:57
  • 2
    As far as I remember from an elder project, the above code will not work when calculating with ISO-Weeks (8601 what is used in europe often) also if the base will be adjusted(see my answer). But maybe this has changed with .net4. – HCL Oct 04 '10 at 11:05
  • Yes, you are correct it doesnt follow the ISO standard. Could be adjusted quite easily to fit with the standard. Will put and correction in. – JDunkerley Oct 04 '10 at 11:19
  • Thanks, I used another function, but the main idea is the same. –  Oct 06 '10 at 20:38
  • I've provided the correct way of computing ISO week dates in my own answer. I find that most people get this wrong and think it's a good idea to keep this code laying around. It doesn't do any weird stuff instead it uses the .NET API as much as possible to get correct results. – John Leidegren Mar 21 '11 at 13:23
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. See this answer for details.

Most people tend to get this wrong and by wrong I mean not conform to the ISO8601 week date (we use this a lot in Sweden) standard. This calculation is kinda strange but it boils down to this code in .NET:

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;

It will compute the date of a year (yyyy), week number (ww) and day of week (d). It does so by first establishing the first of January using the built-in calendar (so this code can be customized). The reason this is a bit strange is because week 53 sometimes occur in January and sometimes week 1 occurs in December.

If you need go the otherway it's not entirely trivial but the correct way to do this in .NET is shown here.

var c = CultureInfo.CurrentCulture.Calendar;

// `FromDayOfWeek` fixes problem with the enumeration
// not based on Monday being the first day of the week
d = (byte)FromDayOfWeek(c.GetDayOfWeek(t));
switch (d)
{
    case 1:
    case 2:
    case 3:
        // see this for details
        // http://blogs.msdn.com/shawnste/archive/2006/01/24/iso-8601-week-of-year-format-in-microsoft-net.aspx
        t = t.AddDays(3);
        break;
}

ww = (byte)c.GetWeekOfYear(t, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

// Adjust year when week 53 occurs in January or week 1 occurs in December 
if (ww == 53 && t.Month == 1)
{
    yyyy = (short)(t.Year - 1);
}
else if (ww == 1 && t.Month == 12)
{
    yyyy = (short)(t.Year + 1);
}
else
{
    yyyy = (short)t.Year;
}
Community
  • 1
  • 1
John Leidegren
  • 59,920
  • 20
  • 131
  • 152
1

The following function will help you to get starting date from week number and year

public DateTime GetFirstDayFromWeekNumber(int weekNumber, int weekYear)
        {
            DateTime beginingYear = new DateTime(weekYear, 1, 1);
            DateTime finalDate = new DateTime();
            int maxDayOfWeek = (int)DayOfWeek.Saturday;
            int yearStartDay = (int)beginingYear.DayOfWeek;
            int dayDeference = maxDayOfWeek - yearStartDay;

            if (weekNumber == 1)
            {
                finalDate = beginingYear.AddDays(-yearStartDay);
            }
            else if (weekNumber == 2)
            {
                finalDate = beginingYear.AddDays((dayDeference + 1));
            }
            else if (weekNumber > 2 && weekNumber <= 53)
            {
                finalDate = beginingYear.AddDays((dayDeference + 1) + ((weekNumber - 2)* 7));
            }
            return finalDate;
        }
user247702
  • 23,641
  • 15
  • 110
  • 157