Erlang Central

Dates and Time

From ErlangCentral Wiki


Erlang provides basic, but important ways of manipulating time and dates. erlang:localtime/0 returns the current time as a tuple of tuples:

1> {Date={Year,Month,Day},Time={Hour,Minutes,Seconds}} = erlang:localtime().
2> b().
Date = {2006,9,25}
Day = 25
Hour = 4
Minutes = 34
Seconds = 29
Time = {4,35,50}
Year = 2006

The erlang:now/0 built-in function returns the current time as a tuple:

3> Now={Megaseconds,Seconds,Microseconds} = erlang:now().

These tuples are based on a platform-specific starting date, or epoch.

Erlang also provides support for Gregorian date and time manipulation by way of the 'calendar' module. The Gregorian calendar in this module is extended back to year 0. For a given date, the gregorian days is the number of days up to and including the date specified. Similarly, the gregorian seconds for a given date and time, is the the number of seconds up to and including the specified date and time.

Since people are not used to working with seconds (or MegaSeconds, for that matter), Erlang provides several convenience functions to convert erlang:now/0 times to date-time values, for example: calendar:now_to_local_time/1, which returns the local date and time converted from the return value from erlang:now/0; and calendar:now_to_universal_time/1, which returns the same for UTC.

4> calendar:now_to_local_time(Now).
5> calendar:now_to_universal_time(Now).

Erlang also provides erlang:date/0, and erlang:time/0, which return the two respective sub-tuples of erlang:localtime/0.

6> [erlang:localtime(), erlang:date(), erlang:time()].