javascript - 将 javascript 时间戳转换为日期元组的可靠方法

标签 javascript date erlang

我想将 javascript 时间戳转换为 erlang 日期。我正在使用 qdate库来帮助我做到这一点,因为它还提供了日期算术函数。

首先在午夜之前调用它的 to_date 函数,然后在午夜之后调用它会导致 24 小时的时间偏移。例如:-

 qdate:to_date(Timestamp div 1000). 

 %% {2015,5,2} before midnight

 qdate:to_date(After_midnight_Timestamp div 1000) 

 %%{2015,5,2} after midnight should be 3 instead of 2

我用谷歌搜索了一下,在 erlang calender docs 中找到了这个

The time functions local_time/0 and universal_time/0 provided in this module both return date and time. The reason for this is that separate functions for date and time may result in a date/time combination which is displaced by 24 hours. This happens if one of the functions is called before midnight, and the other after midnight. This problem also applies to the Erlang BIFs date/0 and time/0, and their use is strongly discouraged if a reliable date/time stamp is required.

我无法理解这一点。 local_time/0universal_time/0 中的哪一个函数总是给出正确的结果?我所说的正确是指我希望在午夜之后显示正确的日期。时间分辨率仅为{y,m,d}。不要关心小时、分钟和秒或任何比这更精细的东西。

那么如何可靠地将 javascript 时间戳转换为 erlang 中的日期?

最佳答案

看起来这只是一个时区问题 :) 因为我使用的是 javascript 时间戳,所以 javscript 时间戳的默认时区是我的 localtimzone,即“IST”。现在在内部,当 qdate 在 qdate:to_date(Timestamp). 中看到一个整数时,它会自动为其选择一个 UTC 时区。相关代码on line 256 :-

raw_to_date(Unixtime) when is_integer(Unixtime) ->
    unixtime_to_date(Unixtime);

%% other clauses

在线654

unixtime_to_now(T) when is_integer(T) ->
    MegaSec = floor(T/1000000),
    Secs = T - MegaSec*1000000,
    {MegaSec,Secs,0}.

unixtime_to_date(T) ->
    Now = unixtime_to_now(T),
    calendar:now_to_datetime(Now).

最后的线索来自erlang calendar文档本身

now_to_datetime(Now) -> datetime1970()

Types: Now = erlang:timestamp()

This function returns Universal Coordinated Time (UTC) converted from the return value from erlang:now().

所以这个问题的解决方案是简单地提供一个带有 qdate:to_date() 的 IST 字符串,就像这样:-

qdate:to_date("IST",Timestamp div 1000)

它开始返回正确的日期。我不确定解决方案,所以我使用 qdate:to_date(erlang:now()) 进行了测试,返回的值恰好比我的时钟时间晚 5:30。所以似乎提供时区字符串是有效的:)

关于javascript - 将 javascript 时间戳转换为日期元组的可靠方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009945/

相关文章:

windows - Windows 应用程序中嵌入的零部署 CouchDB?

java - JSP 不可解析的日期异常

c - unicode 排序规则 NIF 运行速度比纯 Erlang 实现慢

javascript - 如何在 JavaScript 中跟踪一系列按键?

javascript - 在大分辨率下禁用 Bootstrap 3 折叠 Accordion 中的切换选项

javascript - 需要帮助在日语中格式化 MomentJS 中的日期

java - Java 中的顺序日期和时间

erlang - 如何使用 Ecoouch 将 Nitrogen 与 Couchdb 连接

java - 在 Java Web 应用程序中动态添加外部 JavaScript 或 CSS 文件

javascript - 使用 "JavaScript: The Definite Guide"中的 onLoad 函数有什么意义?