I want to get the List of Weeks in a specific year along with Start & End Dates.
I have tried the Solution given in this
which is:
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
});
it is returning Weeks correctly for 2023. But when I select 2020, it takes first day from 2019 & Last day from 2021:
No any week should include the dates from another year in the start/end. For Example if the year starts at Thursday, The previous week will end at Wednesday & new Week will be started from Thursday.
Any suggestions to Resolve this? I want weeks in the same format, just to resolve this start & end issue
Thanks in Advance!
UPDATE:
I have tried the following Code which is getting the correct Start & End Date for the First Week but the Second Week is starting from the End Date of First Week:
var jan1 = new DateTime(year, 1, 1);
var dec31 = new DateTime(year, 12, 31);
CultureInfo cultInfo = CultureInfo.CurrentCulture;
var startOfFirstWeek = jan1.AddDays(0 - (int)(jan1.DayOfWeek));
return Enumerable.Range(0, 54)
.Select(i => new Week
{
StartDate = i == 0
? jan1
: startOfFirstWeek.AddDays(i * 7),
EndDate = startOfFirstWeek.AddDays(i * 7 + 7).Year == year
? startOfFirstWeek.AddDays(i * 7 + 7)
: dec31,
Number = i + 1
})
.TakeWhile(week => week.StartDate.Year == year)
.ToList();