【问题标题】:How to convert datetime() to timestamp() in Erlang/OTP?如何在 Erlang/OTP 中将 datetime() 转换为 timestamp()?
【发布时间】:2020-05-30 03:53:10
【问题描述】:

我需要将{{2012, 9, 21}, {13, 21, 11}} 转换为timestamp()

我该怎么做?

【问题讨论】:

标签: erlang


【解决方案1】:

修正版:

Seconds = calendar:datetime_to_gregorian_seconds(DateTime) - 62167219200,
%% 62167219200 == calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})
{Seconds div 1000000, Seconds rem 1000000, 0}.

【讨论】:

  • 没关系,但请注意,如果您使用函数 erlang:now() 来获取时间戳以进行比较或任何计算,if 将为您提供从 1970 年 1 月 1 日开始的时间估计,而 calendar:datetime_to_gregorian_seconds/1 从 1/1/0 开始进行评估。所以相差719528天……
  • 哎呀,你是对的。而且由于timestamp() 被定义为如果可能的话从 1970 年开始,我的回答是 not ok :)
  • 我试过上面的函数:Timestamp = datetime_to_now({{2012, 9, 21}, {13, 21, 00}}) 然后 calendar:now_to_local_time(Timestamp) 返回 {{2012,9 ,21},{17,21,0}}。我的时区是+4h。据我所知,该函数以 UTC 格式返回时间戳。对吗?
  • @KirillTrofimov 是的,就像now/0 返回的时间戳一样。如果您需要当地时间,请先使用calendar:local_time_to_universal_time_dst/1 进行转换。
【解决方案2】:

你可以用这个

to_timestamp({{Year,Month,Day},{Hours,Minutes,Seconds}}) ->
(calendar:datetime_to_gregorian_seconds(
    {{Year,Month,Day},{Hours,Minutes,Seconds}}
) - 62167219200)*1000000;

这是此模块的一部分 Github/Arboreus

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 2020-12-15
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多