Reputation: 63
I would like to convert the result of erlang:timestamp() to the normal date type, Gregorian Calendar type.
Normal Date type means "Day-Month-Year, Hour:Minutes:seconds".
ExampleTime = erlang:timeStamp(),
ct:pal("~p", [ExampleTime]).
This shows {1568,869478,181646}
I guess the unit is the second, but not sure of what it stands for.
How it can be converted with code and its concept. Be more specific, I do not know but for an example,
{1568, 869478, 181646} == {Year+Month,day,hour+minutes}.
Upvotes: 3
Views: 3849
Reputation: 2345
I've been using this function when it comes to converting to human readable timestamps from erlang:timestamp()
:
format_utc_timestamp(TS, Separator) ->
{_,_,Micro} = TS,
{{Year,Month,Day},{Hour,Minute,Second}} =
calendar:now_to_universal_time(TS),
io_lib:format("~4w-~2..0w-~2..0w~s~2..0w:~2..0w:~2..0w.~6..0w",
[Year,Month,Day,Separator,Hour,Minute,Second,Micro]).
Where TS
is the timestamp value of {MegaSecs, Secs, MicroSecs}
and Separator
is a string to be used to pretty print the timestamp. This will give you the format, with T
as the separator:
2019-09-25T10:19:19.020202
If you'd like to get an ISO 8601 timestamp, you can do the following formatting on the last line of the function above:
io_lib:format("~4w-~2..0w-~2..0wT~w:~2..0w:~2..0wZ", [Year,Month,Day,Hour,Minute,Second])
Which will result in 2014-09-22T20:53:44Z
Upvotes: 1
Reputation: 1449
Here is example of generate ISO 8601 format:
1> {{Year, Month, Day}, {Hour, Min, Sec}} = calendar:now_to_datetime(erlang:timestamp()).
{{2019,9,19},{15,7,3}}
2> list_to_binary(io_lib:format("~.4.0w-~.2.0w-~.2.0wT~.2.0w:~.2.0w:~.2.0w.0+00:00", [Year, Month, Day, Hour, Min, Sec])).
<<"2019-09-19T15:07:03.0+00:00">>
Or you can use erlang:universaltime()
instead calendar:now_to_datetime(erlang:timestamp())
for get universal time
Upvotes: 0
Reputation: 91
here is my code:
{{Y,M,D},{ H,MM,SS}} = calendar:now_to_datetime({MegaSecs,Secs,MicroSecs }),
lists:flatten(io_lib:format("~B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Y, M, D,H,MM,SS])).
% result like 2019-09-18 12:00:00
Upvotes: 1
Reputation: 14042
Please, look at the documentation erlang:timestamp(), it says
erlang:timestamp() -> Timestamp
Types
Timestamp = timestamp()
timestamp() =
{MegaSecs :: integer() >= 0, Secs :: integer() >= 0, MicroSecs :: integer() >= 0}
Returns current Erlang system time on the format {MegaSecs, Secs, MicroSecs}...
Then the module calendar of the stdlib library offers several conversion functions such as calendar:now_to_datetime(Now) :
1> calendar:now_to_datetime({1568,869478,181646}).
{{2019,9,19},{5,4,38}}
Upvotes: 4