Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of weeks for a year - with dates

Tags:

c#

.net

asp.net

I've been racking my brains over this, but it's late on a Friday and I'm going round in circles.

I need to create a list of working weeks for a drop down list, with the week number as the value. So the code would output:

Monday 22nd August - Friday 26th September
Monday 29th August - Friday 2 September
Monday 5th September - Friday 9 September

etc..

For the whole year. Any ideas how I would achieve this?

Thanks.

like image 505
DarrylGodden Avatar asked Sep 09 '11 15:09

DarrylGodden


2 Answers

I think the code below complies with ISO 8601:

var jan1 = new DateTime(DateTime.Today.Year , 1, 1);
//beware different cultures, see other answers
var startOfFirstWeek = jan1.AddDays(1 - (int)(jan1.DayOfWeek));
var weeks=
    Enumerable
        .Range(0,54)
        .Select(i => new {
            weekStart = startOfFirstWeek.AddDays(i * 7)
        })
        .TakeWhile(x => x.weekStart.Year <= jan1.Year)
        .Select(x => new {
            x.weekStart,
            weekFinish=x.weekStart.AddDays(4)
        })
        .SkipWhile(x => x.weekFinish < jan1.AddDays(1) )
        .Select((x,i) => new {
            x.weekStart,
            x.weekFinish,
            weekNum=i+1
        });
like image 133
spender Avatar answered Sep 26 '22 03:09

spender


Bear in mind, that week calculations are done differently in different cultures and there is not a bug if you see week number 53!

using System.Globalization;

CultureInfo cultInfo = CultureInfo.CurrentCulture;
int weekNumNow = cultInfo.Calendar.GetWeekOfYear(DateTime.Now,
                     cultInfo.DateTimeFormat.CalendarWeekRule,
                         cultInfo.DateTimeFormat.FirstDayOfWeek); 
like image 42
IrishChieftain Avatar answered Sep 22 '22 03:09

IrishChieftain