c++windowsalgorithmtime

How do I calculate the week number given a date?


If I have a date, how do I calculate the week number for that date within that year?

For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.

An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.

Related:

Getting week number off a date in MS SQL Server 2005?


Solution

  • Pseudocode:

    int julian = getDayOfYear(myDate)  // Jan 1 = 1, Jan 2 = 2, etc...
    int dow = getDayOfWeek(myDate)     // Sun = 0, Mon = 1, etc...
    int dowJan1 = getDayOfWeek("1/1/" + thisYear)   // find out first of year's day
    // int badWeekNum = (julian / 7) + 1  // Get our week# (wrong!  Don't use this)
    int weekNum = ((julian + 6) / 7)   // probably better.  CHECK THIS LINE. (See comments.)
    if (dow < dowJan1)                 // adjust for being after Saturday of week #1
        ++weekNum;
    return (weekNum)
    

    To clarify, this algorithm assumes you number your weeks like this:

    S  M  T  W  R  F  S
                1  2  3    <-- week #1
    4  5  6  7  8  9 10    <-- week #2
    [etc.]
    

    getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages. If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.

    If you're going to implement your own date counting routines, remember that years that are divisible by 100 are NOT leap years, unless they are also divisible by 400. So 1900 was not a leap year, but 2000 was. If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see Wikipedia for loads of info on that.

    This link talks about date/time functions in Windows/C++ in greater detail.