Determining the week of a year from a given date

Since I'm living in Europe I'm sticking to the European definition of week number which is equivalent to the ISO standard. According to this standard, a week starts on Monday and the first week is the week containing 4 January. Taking this into account you could do therefore do something like

weekNumberISO[date_] := Module[{day0, year},
  With[{days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}},
   year = ToExpression[DateString[date, "Year"]] ; 
   day0 = DatePlus[{year, 1, 4}, 
      {1 - Position[days, DateString[{year, 1, 4}, "DayNameShort"]][[1, 1]], "Day"}];
   1 + Floor[DateDifference[day0, date, "Week"][[1]]]]]

For the North-American definition of week number, i.e. week 1 is the week containing 1 January and a week starts on Sunday, you would get something like

weekNumberUS[date_] := Module[{day0, year},
  With[{days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}},
   year = ToExpression[DateString[date, "Year"]] ; 
   day0 = DatePlus[{year, 1, 1}, 
      {1 - Position[days, DateString[{year, 1, 1}, "DayNameShort"]][[1, 1]], "Day"}];
   1 + Floor[DateDifference[day0, date, "Week"][[1]]]]]

You can use DateDifference to find the time between January 1st and April 17th:

DateDifference["Jan. 1", "April 17", "Week"]

(* {15.2857, "Week"} *)

If you want the "week number" as you've put it, you can just do:

Ceiling@First@DateDifference["Jan. 1", "April 17", "Week"]

which gives 16.

Edit based on Szabolcs's comment: To ensure this works for Jan 1., use

1 + Floor@First@DateDifference["Jan. 1", "Jan. 1", "Week"]

which gives 1 rather than 0 from the Ceiling approach.


If you want it to automatically pull the current date, use the DateList function:

DateDifference["Jan. 1", DateList[], "Week"]

(* {15.782, "Week"} *)

And finally: this works in Mathematica running on Mac OS X - it's getting the ISO Week number from the Unix shell:

<< "! date -j '+%V'"

16

Although I can't see how to test it without changing the system clock... :)