[erlang-questions] Date Conversion

Richard O'Keefe ok@REDACTED
Wed Nov 14 23:04:13 CET 2012

On 14/11/2012, at 10:26 PM, Lucky Khoza wrote:

> Hi Erlang Developers,
> How do i convert date string: "2012/02/15" to 2012/2/15, just to get rid of trailing Zero.

(1) There is no trailing zero there.
(2) Date standards like ISO 8601 often *require* the leading zero.
    {ok,[Y,M,D],[]} = io_lib:fread("~d/~d/~d", "2012/02/15"),
    lists:flatten(io_lib:fwrite("~w/~w/~w", [Y,M,D])) 
If you just want to write the result, you can use io:fwrite/[2,3]
instead of io_lib:fwrite/2.

In one sense, Erlang resembles C:  formatted input and formatted
output use formats that _look_ similar at first glance but are
really quite different.

Or you could think in terms of a finite state automaton
with two fairly obvious states.

strip_leading_zeros([$0|Cs]) ->
strip_leading_zeros([D|Cs]) when D =< $9, D >= $1 ->
strip_leading_zeros([C|Cs]) ->
strip_leading_zeros([]) ->

after_leading_zeros([D|Cs]) when D =< $9, D >= $0 ->
after_leading_zeros([C|Cs]) ->
after_leading_zeros([]) ->

Basically, in a block of digits, leading zeros are removed,
except that if all digits in the block are zero, one zero
remains.  Non-digit characters are copied and separate blocks.

The version with the finite state automaton is almost
certainly more economical, but the version using formatting
is probably easier to think of and easier to debug.

More information about the erlang-questions mailing list