Simon B - 1 year ago 54
C# Question

# Calculating the week number for a date, when your year starts on a non 1st January day

I need to calculate the week number for a given date, when my year begins on the 1st of May.

My hope was to use

`Calendar.GetWeekOfYear()`
, which applies the rules I need, but by overriding the first day of year in a
`Calendar`
that derives from say,
`GregorianCalendar`
.

Unfortunately I can't find a way of doing this. Adding an arbitrary 122 / 123 days to the date in question will break the
`GetWeekOfYear()`
`CalendarWeekRule.FirstFourDayWeek`
rule I wish to use.

Short of writing a custom and I suspect messy algorithm to determine this, is there a way of calculating the week number for a given date, when my year begins on the 1st of May?

Answer Source

Maybe you could use this approach which simply subtracts the 121 days from January 1st to May 1st from a given `DateTime` and then uses `Calendar.GetWeekOfYear` on that date:

``````static readonly int DayOffset = (new DateTime(DateTime.Today.Year, 5, 1)
- new DateTime(DateTime.Today.Year, 1, 1)).Days; // 121

// ... somewhere else:
DateTime date = DateTime.Today;
DateTime offsetDate = date.AddDays(-DayOffset);
int weekNum = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(offsetDate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
Console.WriteLine("Year:{0} Week:{1}", offsetDate.Year, weekNum); // Year:2016 Week:19
``````