e r l a n g : c o o k b o o k

/ Erlang.TimeWeekOfTheYear

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Week of the Year, and Day of the Week/Month/Year

Problem

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.

Solution

Luckily, this functionality is all supplied in the calendar module.

1> {Today,Time} = erlang:universaltime().
{{2004,8,28},{7,59,8}}
2> DayOfWeek = calendar:day_of_the_week(Today).
6
3> {_, Month, DayOfMonth} = Today.
{2004,8,28}
4> DayOfMonth.
28
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).
"Sat"
6> MonthName = httpd_util:month(Month).
"Aug"
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).
731946
8> TodayDay = calendar:date_to_gregorian_days(2004,Month,DayOfMonth).
732064
9> DayOfYear = TodayDay - Day0.
118
Note: 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).
31
11> calendar:last_day_of_the_month(2004,2).
29
12> calendar:last_day_of_the_month(2005,2).
28

Discussion

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.

See Also

Comments here

Based on work by FranciscoSolsona.

-- BrentAFulgham - 28 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: TimeRecipes
TopicOrder: 070

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest