Reputation: 61483
I am saving data into a circular log with designated byte multiples (dataSlots), and I'm calculating the week number based on the days that pass from a reference date.
DateTime startDate = DateTime.UtcNow;
for (int ii = 0; ii < 900; ii++)
{
currentDate = startDate + new TimeSpan(7 * ii, 1, 1, 1, 1)
DateTime globalStartReference = new DateTime(2011, 12, 1, 0, 0, 0, DateTimeKind.Utc);
var span = currentDate - globalStartReference ;
int dataSlot = 0;
dataSlot = (span.Days * 7) / 52;
Console.WriteLine(dataSlot);
}
My hope is that dataSlot will be an ever-increasing number based upon the current week, however it isn't. I get duplicate entries (and therefore overwrite my data) on these weeks
11
28
44
60
77
88
109
Why am I getting duplicate weeks and how do I account for this? My guess is that there is a fractional number of weeks in a year...
Upvotes: 0
Views: 428
Reputation: 3647
If you're just worried about weeks from baseline, years don't enter into it - it's just 7-day increments.
Otherwise you have year and week-of-year; @BACON's answer is probably right for this. You'll get a bit of overlap - Y2W1 may share the same calendar week as Y1W52. Dunno if you'll just add and make that Week 53 but this gets problematic the longer you go.
Upvotes: 0
Reputation: 16612
The Calendar.GetWeekOfYear method may be helpful. It doesn't allow for an arbitrary reference date, however you could adjust for that yourself.
Upvotes: 5
Reputation: 1120
Are you trying to get the current week for any given year? It looks like from some pre-defined start date ad infinitum. Using the appropriate calendar, and methods it it, you can get a given week of the year based on a particular date, but not x weeks from any arbitrary date.
Plus you need to account for leap years, partial weeks, etc.
Upvotes: 1