Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erlang:now to timestamp and back again

In my project erlang:now is converted to a high precision timestamp (bigint) for storage in MySQL:

timestamp({Mega, Secs, Micro}) ->
    Mega*1000*1000*1000*1000 + Secs * 1000 * 1000 + Micro.

I now convert the timestamp back to the orginal {Mega, Secs, Micro} tuple using:

time_tuple(Timestamp) ->
    TimeList = erlang:integer_to_list(Timestamp),
    Mega = erlang:list_to_integer(string:substr(TimeList, 1, 4)),
    Sec = erlang:list_to_integer(string:substr(TimeList, 5, 6)),
    Micro = erlang:list_to_integer(string:substr(TimeList, 11, 6)),
    {Mega, Sec, Micro}.

The string conversion / substr feels like an ugly, and possible incorrect, hack. What would be a more elegant way?

like image 908
Ward Bekker Avatar asked Dec 09 '22 02:12

Ward Bekker


1 Answers

I might be missing something, but why don't you just use division and modulo for that?

> {Mega, Sec, Micro} = now().
> Timestamp = Mega * 1000000 * 1000000 + Sec * 1000000 + Micro.
> {Mega1, Sec1, Micro1} = {Timestamp div 1000000000000, 
                            Timestamp div 1000000 rem 1000000,
                            Timestamp rem 1000000}.
like image 73
Łukasz Milewski Avatar answered Dec 19 '22 01:12

Łukasz Milewski