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!
2
Answers
You have to change your code to make exceptions for the first and last weeks. For the first, you set the start at jan1 and for the last you remove all days going on next year.
Thank you for clarifying your question, I think I understand what you want. The first week of the year should start on January 1st, and the last week should end on December 31st.
The way I would solve this is to first of all use an actual class instead of an anonymous type to represent a week (which has a
Number
, aStartDate
, and anEndDate
):Then we can create a method to populate a list of weeks for a specified year.
In the method, as we enumerate each week, we set the start date to either January 1st (if it’s the first week) or we calculate the start date based on the actual first day of the first week (which may be in the previous year) as we were doing before.
We also ensure that we set the last day of the last week to December 31st, by checking if the actual last day of the week has a year greater than the one passed into our method. Otherwise we just use the result of adding
6
to theStartDate
.Also, I’m not sure why your code has so many
Select
statements – you can just select each week once, populating theStartDate
,EndDate
, andNumber
all in one go.For example: