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

/ Erlang.TimeToday

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

Finding Today's Date

Problem

You need to find the year, month, and day values for today's date.

Solution

Use erlang:now(), and now_to_datetime to get a date structure type representing today.

1> {{Year,Month,Day},_} = calendar:now_to_datetime(erlang:now()).
{{2004,8,27},{23,33,40}}

Discussion

Using the io or io_lib module, you can easily convert a date structure to a string.

% Note:  This example uses the above form to bind Year, Month, and Day
2> io:fwrite("Today's Date is ~2B/~2B/~4B\n",
2>       [Month, Day, Year]).
Today's Date is  8/27/2004
ok

We can get fancier and show the time as well.

3> {{Year,Month,Day},{Hour,Min,Sec} = 
3>    calendar:now_to_datetime(erlang:now()).
{{2004,8,27},{23,33,40}}
4> io:fwrite("Today's Date is ~2B/~2B/~4B ~2B:~2.10.0B:~2.10.0B\n",
4> [Month, Day, Year, Hour, Min, Sec]).                            
Today's Date is  8/27/2004 23:59:06

Note the use of the three-part B format specification. The first part is the number of digits to show (2), the second is the base of the number (decimal in this case), and the third is a character to fill any single-digit numbers with (in this case, we want leading zeros).

Ideally, it would be nice if a few convenience functions were available to provide locale-specific date and time formats, but these do not seem to be present in Erlang at this time.

This is extra sad for developers dealing with varying cultures, where dates and time are printed in different formats (Canada: DD/MM/YYYY; US: MM/DD/YYYY; Scandinavia: YYYY-MM-DD; Germany: DD.MM.YYYY; etc). For embedded systems, this may not be so bad, but for user-visible systems like MochiWeb?, it starts to hurt to have to build these yourself.

See Also

Comments here

Based on work by FranciscoSolsona.

-- BrentAFulgham - 27 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: TimeRecipes
TopicOrder: 010

 
 
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