Erlang: How to convert erlang date to binary?

954 views Asked by At

I have the following function that returns current date:

7> {Y,M,D}=erlang:date().
{2014,11,18}

Now I need to have a binary with these values inside like this:

<<"20141118">>

I have tried

15> S= [Y,M,D].
[2014,11,18]
16> list_to_binary(S).
** exception error: bad argument
 in function  list_to_binary/1
    called as list_to_binary([2014,11,18])
5

There are 5 answers

1
Shkodran Gerguri On BEST ANSWER

You can do it like this:

9> list_to_binary(lists:map(fun erlang:integer_to_list/1, [Y, M, D])).
<<"20141118">>

Or like this, which is equivalent but not really practical for larger lists:

10> list_to_binary([integer_to_list(Y), integer_to_list(M), integer_to_list(D)]).
<<"20141118">>
0
BlackMamba On
{Y,M,D}=erlang:date().
list_to_binary( io_lib:format("~p~p~p", [Y,M,D]) ).

The output is <<"20141119">>.

You can try this method.

0
Pascal On

You should add separators in your binary or at least format it otherwise you will not be able to make the difference between 2014/12/09 and 2014/01/29 with the binary <<"2014129">>. You could use:

list_to_binary(io_lib:format("~4w~2w~2w", [Y,M,D])).  % which will add space when necessary

Or if you only want to store the information you can store each element as a 16 bit binary:

lists:foldr(fun(X,Acc) -> <<X:16,Acc/binary>> end,<<>>,[Y,M,D]). % the result is less friendly to read but easier to manipulate.

Result:

1> list_to_binary(io_lib:format("~4w~2w~2w",[2014,1,11])).   
<<"2014 111">>
2> lists:foldr(fun(X,Acc) -> <<X:16,Acc/binary>> end,<<>>,[2014,1,11]).
<<7,222,0,1,0,11>>
3> 
0
afsantos On

Try the following function, based on the answers to this question, and this question.

date_to_binary() ->
    {Y,M,D} = erlang:date(),
    BinY = list_to_binary(integer_to_list(Y)),
    BinM = list_to_binary(integer_to_list(M)),
    BinD = list_to_binary(integer_to_list(D)),
    <<BinY/binary, BinM/binary, BinD/binary>>.

This may not be the most efficient method, but it is probably the most explicit step by step conversion available out of the box.

0
chops On

Late response, but why not:

Another single line option using qdate (a project of mine):

qdate:to_string(<<"Ymd">>, {erlang:date(), {0,0,0}}).

qdate:to_string's formatting option follows PHP's date() function formatting conventions. The addition of {0,0,0} is necessary because a three-tuple is treated as an erlang timestamp (now() format) while a two-tuple of three-tuples (ex: {{2015, 9, 30}, {15, 54, 39}}) is needed for it to identify a date format.