Erlang Central

Week of the Year and Day of the Week Month Year

Revision as of 18:04, 30 November 2010 by Imrehorvath (Talk | contribs)


Given a date, you need to find out what week of the year, day of the week, day of the month, or day of the year that the date falls on.


Almost all of these functionality are available using the calendar module, directly or indirectly. Namely the day of the week, month and year but not the week number.

1> {Today,Time} = erlang:universaltime().
2> DayOfWeek = calendar:day_of_the_week(Today).
3> {_, Month, DayOfMonth} = Today.
4> DayOfMonth.

If you wanted to get the text string representing the day or the month, you can use the httpd_util module (which contains all sorts of useful things that should be moved to the calendar and string modules:

5> DayName = httpd_util:day(DayOfWeek).
6> MonthName = httpd_util:month(Month).

Unfortunately, there are no built-in functions for identifying the week of the year, or the day of the year (directly). However, by doing a bit of math we can figure out at least the day of the year:

7> Day0 = calendar:date_to_gregorian_days(2004,1,1).
8> TodayDay = calendar:date_to_gregorian_days(2004,Month,DayOfMonth).
9> DayOfYear = TodayDay - Day0.

Note1: However if you need the week number, you can look around among the User Contributions and/or GitHub for Erlang projects (eg. iso_8601_erl) implementing this missing feature.

Note2: Please keep in mind that there are standard (ISO 8601) and non-standard definition of week numbers. You should know which one you need!

One very useful thing (beloved of Financial Systems Programmers everywhere) is that Erlang has an end-of-month function:

10> LastDayOfMonth = calendar:last_day_of_the_month(2004, 8).
11> calendar:last_day_of_the_month(2004,2).
12> calendar:last_day_of_the_month(2005,2).

If you are wondering what to use when you are using the Epoch (seconds) representation of the given date, then you should consider transforming your number of seconds to date, and then use this recipe. See recipe TimeEpochToTime to pass from seconds to dates.