2012-02-29 33 views
4

在我的项目二郎:现在转化为高精度时间戳(BIGINT)存储在MySQL:二郎:现在时间戳,然后再返回

timestamp({Mega, Secs, Micro}) -> 
    Mega*1000*1000*1000*1000 + Secs * 1000 * 1000 + 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}. 

串转换/ SUBSTR感觉难看,和可能的不正确,黑客攻击。什么会是更优雅的方式?

回答

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}. 
+3

是偏离正轨。我猜想需要更多的咖啡;-) – 2012-02-29 08:57:50