0

How do you calculate the amount of weeks between 2 ISO8601 dates using only the week and year number?

Input: year1 week1 year2 week2

Output: Amount of weeks according to ISO8601

I can calculate the amount of weeks in a year:

public static int AmountOfWeeksInYearIso8601(this DateTime dateTime)
{
    var year = dateTime.Year;
    var g = Math.Floor((year - 100d) / 400d) - Math.Floor((year - 102d) / 400d);
    var h = Math.Floor((year - 200d) / 400d) - Math.Floor((year - 199d) / 400d);
    var f = 5 * year + 12 - 4 * (Math.Floor(year / 100d) - Math.Floor(year / 400d)) + g + h;

    return f % 28 < 5 ? 53 : 52;
}
Barsonax
  • 197
  • 2
  • 12
  • 1
    That's a bit confusing, as week number and a year don't make up a date - can you clarify your question a bit more? – stuartd Dec 16 '16 at 15:19
  • 2
    @stuartd "allowing for the years" is enough to make this non-trivial: it requires figuring out which years have 52 weeks and which have 53. –  Dec 16 '16 at 15:21
  • @stuartd In the ISO week numbering, that might fall in week 1 of the next year. –  Dec 16 '16 at 15:23
  • @hvd OK i give up :) – stuartd Dec 16 '16 at 15:24
  • @Liam That's about ISO 8601 year-month-day format, not ISO 8601 year-week format. Same ISO standard, very different questions. :) –  Dec 16 '16 at 15:30
  • Something like: `int weeks = (WeeksIn(startYear) - startWeek) + endWeek; for(int theYear = startYear + 1; theYear < endYear; theYear++) { weeks += WeeksIn(theYear); }` maybe? -- some `+/-1` might be needed in some places... – Corak Dec 16 '16 at 15:47
  • @Corak i thought of using itteration but its not very performant when working with long periods since O(n). – Barsonax Dec 16 '16 at 16:00

1 Answers1

4

Create DateTime values corresponding to the Mondays of the two weeks. See Calculate date from week number for how to do this. Subtract these to get the difference as a TimeSpan. Request its Days property to get the difference as a number of days. Divide by 7 to get the difference as a number of weeks.

Community
  • 1
  • 1
  • Btw. this is also definitely faster than iteration in most cases. Checking `year % 400` against a hashset as suggested in http://stackoverflow.com/a/8724110/1336590 is slightly faster for differences less than about 30 years. After that, iteration gets slower and slower, while this seems to have constant execution time. – Corak Dec 17 '16 at 13:50