Reputation: 1096
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?
Upvotes: 0
Views: 107
Reputation: 1096
I ended up with this, which works but doesn't handle the week 53 scenario:
private int calculateBizWeekNumber(DateTime date, DateTime yearStart, CalendarWeekRule cwr, DayOfWeek firstDoW)
{
var cal = DateTimeFormatInfo.CurrentInfo.Calendar;
var dateWoY = cal.GetWeekOfYear(date, cwr, firstDoW);
var firstWoY = cal.GetWeekOfYear(yearStart, cwr, firstDoW);
var bizWeek = dateWoY - firstWoY + 1;
return bizWeek <= 0 ? 52 + bizWeek : bizWeek;
}
Upvotes: 0
Reputation: 460058
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
Upvotes: 1