erlang:现在再来一次时间戳

War*_*ker 4 erlang timestamp unix-timestamp

在我的项目erlang中:现在转换为高精度时间戳(bigint)以便在MySQL中存储:

timestamp({Mega, Secs, Micro}) ->
    Mega*1000*1000*1000*1000 + Secs * 1000 * 1000 + Micro.
Run Code Online (Sandbox Code Playgroud)

我现在使用以下命令将时间戳转换回原始的{Mega,Secs,Micro}元组:

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}.
Run Code Online (Sandbox Code Playgroud)

字符串转换/ substr感觉就像一个丑陋的,可能不正确的黑客.什么是更优雅的方式?

Łuk*_*ski 14

我可能会遗漏一些东西,但你为什么不只使用除法和模数?

> {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}.
Run Code Online (Sandbox Code Playgroud)

  • 是的,当然.我猜需要更多的咖啡;-) (3认同)