abasi anis
abasi anis

Reputation: 29

date conversion in erlang

I developed this function :

get_data_by_transaction(TransactionCode)->

 Q = qlc:q([{X#transaction.datetime} || X <- mnesia:table(transaction),
                X#transaction.transaction_code =:= TransactionCode]),
    case do(Q) of
        [{K}] ->  
        {ok, K};

        [] ->
            {error, notfound}
    end.

when I test this function I have this result :

{ok,{{2013,3,6},{7,12,49}}}

my goal is to have this kind of result :

06/03/2013 7:12

so I should convert my data to be in the new format

can sameone help me to solve my problem

I try with this code :

format_date({{Year, Month, Day}, {Hour, Minute, _}}) ->
    lists:flatten(
        io_lib:format("~2..0B/~2..0B/~4..0B ~B:~2..0B", [Day, Month, Year, Hour,Minute])). 

and when I run this code I have :

3> format_date({{2013,3,6},{7,12,3}}).           
"06/03/2013 7:12"

but my goal id not to display this result but to associate this result to a variable

I will try to follow the links which are in the previous response

Upvotes: 2

Views: 238

Answers (1)

Martin T&#246;rnwall
Martin T&#246;rnwall

Reputation: 9599

If the desired output format is as simple as it looks from your example, an io_lib:format/2 with the appropriate padding will do the trick:

format_date({{Year, Month, Day}, {Hour, Minute, _}}) ->
    lists:flatten(
        io_lib:format("~2..0B/~2..0B/~4..0B ~B:~2..0B", [Day, Month, Year, Hour, Minute])).

Apologies for the long line -- unfortunately, this is what you get with Erlang's format specifiers. If you want to learn more about them, see this post and the documentation. Expect to return to this documentation every time you need to do something fancy with the formatting functions. It simply doesn't stick.

The call to lists:flatten/1 is required because io_lib:format/2 returns a nested list, presumably for performance reasons since the output will frequently be sent to functions that accept iolists.

Also note that before sending the tuple in your example to the function above, you'll need to get rid of the leading ok. Simply matching it as {ok, DateTime} = get_data_by_transaction(...) will get it done.

Upvotes: 2

Related Questions