Week number vs. Erlang/OTP

Some years ago I had to find out what is the current week number for some reason.

Of course there are common tools like Office/Calendar applications and also the Web for your aid. You can look it up easily. Also there are support for it in many programming language libraries.

However, that time I was working on some Erlang research and found that it’s standard library did lack support for determining week numbers. Then I decided to add it since it did sound like a fun little project and a nice experience in Open Source project contribution.

So I began by researching how to determine week numbers. I found that there are different kind of “week numbers” used by different parts of the World. I found that it’s the ISO Week Number I was looking for.

Then I read the well made contribution description/guideline by Ericsson and based on that I made my contribution to Erlang/OTP with the source, documentation and tests.

The contribution was accepted and is part of the Erlang/OTP now. It serves the needs of people developing Erlang applications and wanting to use the Week Number for some reason.

The code in Erlang looks like this:

%%
%% Calculates the iso week number for the current date.
%%
-spec iso_week_number() -> yearweeknum().
iso_week_number() ->
    {Date, _} = local_time(),
    iso_week_number(Date).


%%
%% Calculates the iso week number for the given date.
%%
-spec iso_week_number(Date) -> yearweeknum() when
      Date :: date().
iso_week_number({Year, Month, Day}) ->
    D = date_to_gregorian_days({Year, Month, Day}),
    W01_1_Year = gregorian_days_of_iso_w01_1(Year),
    W01_1_NextYear = gregorian_days_of_iso_w01_1(Year + 1),
    if W01_1_Year =< D andalso D < W01_1_NextYear ->
	    % Current Year Week 01..52(,53)
	    {Year, (D - W01_1_Year) div 7 + 1};
	D < W01_1_Year ->
	    % Previous Year 52 or 53
	    PWN = case day_of_the_week(Year - 1, 1, 1) of
		4 -> 53;
		_ -> case day_of_the_week(Year - 1, 12, 31) of
			4 -> 53;
			_ -> 52
		     end
		end,
	    {Year - 1, PWN};
	W01_1_NextYear =< D ->
	    % Next Year, Week 01
	    {Year + 1, 1}
    end.

References

Week number vs. Erlang/OTP