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.
I strongly recommend using the C Standard Library's time functions to calculate the week number. Specifically, the
strftime
function has specifiers to print the week number (among many other values) given a date in broken-down (struct tm
) format. Here's a small sample program that illustrates this:The output from this program (compiled with GCC on Linux and Microsoft Visual Studio 2005 SP1 on Windows) is:
You can learn more about strftime here.
My assumption was that the first week on the year may contain up to 7 day as illustrated in Olie's answer. The code does not handle the cultures where the week starts on another day than Sunday and that is a large part of the world.
To convert in both directions, see here: Wikipedia article on ISO week dates
invoke as Weekno(2015,12,23,1); //For ISO week number. Weekno(2015,12,23,0) //For non ISO week number
Boost provides gregorian::date::week_number() see http://www.boost.org/doc/libs/1_38_0/doc/html/boost/gregorian/date.html and http://www.boost.org/doc/libs/1_38_0/boost/date_time/gregorian/greg_date.hpp.
However I cannot see a way to get the year number which matches the week number (which may be different to the calendar year for that date).
My definition which is non-ISO 8601 (good enough for my purposes and fast):