我想获取当前时间,并按以下方式格式化:
<块引用>yyyy-MM-dd'T'HH:mm:ss.SSSZ
(其中 SSS 是毫秒,Z 是时区)
到目前为止我的代码如下:
formatted_date() ->
{{Y,M,D},{H,Min,S}} = erlang:localtime(),
{Ms, _, _} = os:timestamp(),
{Days, {Hours, _,_}} = calendar:time_difference(erlang:universaltime(), erlang:localtime()),
Difference = 24*Days + Hours,
Tz = [case Difference < 0 of
true ->
$-;
false ->
$+
end | io_lib:format("~2..0B00",[Difference])],
io_lib:format("[~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0B.~3..0B ~5.s]",
[Y, M, D, H, Min, S, Ms, Tz]).
事实是它总是返回相同的Ms,因此,我认为我做得不好,在其他问题中我只看到如何获得以毫秒为单位的总时间,而不是如何在此格式化方式。
谢谢。
答案 0 :(得分:1)
最简单的方法是使用库函数 calendar:system_time_to_rfc3339/2
- 它似乎可以满足您的所有要求。
> calendar:system_time_to_rfc3339(os:system_time(millisecond), [{unit, millisecond}]).
"2021-03-03T18:42:08.497+05:30"
此功能是在 2018 年 6 月发布的 Erlang/OTP 21.0 中添加的。
您的代码总是为 Ms
获取相同值的原因是 os:timestamp/0
返回的元组中的第一个值是 兆秒,而不是毫秒;这三个值是兆秒、秒和微秒。这来自于 Erlang 不支持大整数的时候,因此拆分时间戳是必要的。如今,您只需调用 os:system_time/1
或 a number of other functions, depending on what kind of time you need,即可获得单个整数的结果。