Epoch in Erlang

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Erlang.

-module(epoch).
-export([main/0]).

main() ->
    % Use erlang:system_time/1 to get elapsed time since the Unix epoch
    % in seconds, milliseconds or nanoseconds.
    Now = erlang:system_time(second),
    io:format("~p~n", [calendar:system_time_to_universal_time(Now)]),

    io:format("~p~n", [erlang:system_time(second)]),
    io:format("~p~n", [erlang:system_time(millisecond)]),
    io:format("~p~n", [erlang:system_time(nanosecond)]),

    % You can also convert integer seconds or nanoseconds
    % since the epoch into the corresponding datetime.
    SecondsSinceEpoch = erlang:system_time(second),
    NanosSinceEpoch = erlang:system_time(nanosecond),
    
    io:format("~p~n", [calendar:system_time_to_universal_time(SecondsSinceEpoch)]),
    io:format("~p~n", [calendar:system_time_to_universal_time(NanosSinceEpoch, nanosecond)]).

To run the program:

$ erlc epoch.erl
$ erl -noshell -s epoch main -s init stop
{{2023,5,15},{12,34,56}}
1684154096
1684154096123
1684154096123456789
{{2023,5,15},{12,34,56}}
{{2023,5,15},{12,34,56}}

In Erlang, we use erlang:system_time/1 to get the current system time in various units. The calendar:system_time_to_universal_time/1 and calendar:system_time_to_universal_time/2 functions are used to convert system time to datetime tuples.

Next, we’ll look at another time-related task: time parsing and formatting.