0

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...

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
makerofthings7
  • 60,103
  • 53
  • 215
  • 448

3 Answers3

5

The Calendar.GetWeekOfYear method may be helpful. It doesn't allow for an arbitrary reference date, however you could adjust for that yourself.

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
1

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.

Jared Peless
  • 1,120
  • 9
  • 11
  • What methods are available to determine week of year? I don't see them under DateTime. I need to get the sum of all weeks from a given start date (fixed, system defined or not), to a user supplied end date. – makerofthings7 Dec 06 '11 at 04:28
  • Well, it would probably involve the Calendar class... but have you also checked out http://stackoverflow.com/questions/1083955/how-to-get-difference-between-two-dates-in-year-month-week-day – Jared Peless Dec 06 '11 at 04:36
0

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.

DaveE
  • 3,579
  • 28
  • 31