Erlang: now to timestamp and vice versa

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

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

Now I will convert the timestamp back to the original {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}. 

Converting strings / substr looks like an ugly and possible wrong hack. What would be a more elegant way?

+4
source share
1 answer

Maybe something is missing for me, but why don't you just use division and module for this?

 > {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}. 
+14
source

Source: https://habr.com/ru/post/1398967/


All Articles