Erlang Central

Converting Between struct:time and ISO8601 Format

From ErlangCentral Wiki


You have an application that requires you to use ISO-8601 Format for input and output.


Unfortunately, no Erlang libraries provide this functionality. Luckily, the native Erlang date and time formats are very easy to format for display or transmission, even in ISO-8601 format:


iso_8601_fmt(DateTime) ->
    {{Year,Month,Day},{Hour,Min,Sec}} = DateTime,
    io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B",
        [Year, Month, Day, Hour, Min, Sec]).

format_iso8601() ->
    {{Year, Month, Day}, {Hour, Min, Sec}} =
        [Year, Month, Day, Hour, Min, Sec] )).

Using the above module:

1> {{Year,Month,Day},{Hour,Min,Sec}} = erlang:localtime().
2> io:fwrite("~s\n",[iso_fmt:iso_8601_fmt(erlang:localtime())]).
2004-08-28 01:48:48

However, if you're writing a web application, you may need to observe the W3C profile for time formats, which is slightly different. See the RFC1123_Dates_and_Times Recipe for details.

The nice thing about the W3C profile of the ISO 8601 format is that it's very easy to sort dates using a simple string compare.