[erlang-questions] NTP timestamp

5 views
Skip to first unread message

József Bérces

unread,
Dec 27, 2007, 6:39:22 PM12/27/07
to erlang-q...@erlang.org

Hi,

I would like to convert NTP timestamps (seconds elapsed since 00:00:00 January 1st, 1900) to Erlang date/time tuples (UTC). I did not find any such functions in the OTP libraries. It seems that there is no function for converting now() to UTC date and time, either.

Any help would be welcome.

Thanks,
Jozsef

Håkan Stenholm

unread,
Dec 27, 2007, 7:02:04 PM12/27/07
to József Bérces, erlang-q...@erlang.org
something like this should work, to convert
NTP timestamps (in UTC) to {date(), time()} in UTC:


%% returns: {date(), time()}
NTPtimestamps_to_datetime(NTPSeconds) ->
%% 1900:01:01 00:00:00 in gregorian seconds
NTPBase = calendar:datetime_to_gregorian_seconds({1900,1,1}, {0,0,0}),
GregorianSec = NTPBase + NTPSeconds,
calendar:gregorian_seconds_to_datetime(Seconds).

the calendar module has the following functions for converting now() to
UTC {date(), time()}:

now_to_universal_time(Now) -> {Date, Time}
now_to_datetime(Now) -> {Date, Time}


> Thanks,
> Jozsef
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> erlang-questions mailing list
> erlang-q...@erlang.org
> http://www.erlang.org/mailman/listinfo/erlang-questions

Serge Aleynikov

unread,
Dec 27, 2007, 11:16:57 PM12/27/07
to József Bérces, erlang-q...@erlang.org
Here's a snippet that deals with time conversion from/to SNTP
timestamps. In the first function Sec and USec are integers in NTP format.

sntp_time_to_now(Sec, USec) ->
case Sec band 16#80000000 of
0 -> Time = Sec + 2085978496; % use base: 7-Feb-2036 @ 06:28:16 UTC
_ -> Time = Sec - 2208988800 % use base: 1-Jan-1900 @ 01:00:00 UTC
end,
{Time div 1000000, Time rem 1000000, round((USec * 1000000) / (1
bsl 32))}.

now_to_sntp_time({_,_,USec} = Now) ->
SecsSinceJan1900 = 16#80000000 bor

(calendar:datetime_to_gregorian_seconds(calendar:now_to_universal_time(Now))
- 59958230400),
{SecsSinceJan1900, round(USec * (1 bsl 32) / 1000000)}.

Serge

Torben Hoffmann

unread,
Dec 28, 2007, 5:19:02 PM12/28/07
to József Bérces, erlang-q...@erlang.org
Try looking at http://www.trapexit.org/Todays_Date and you can use now_to_universal_time/1 as well - you have to read the manual for calendar ( http://www.erlang.org/doc/man/calendar.html) for the details.

Cheers,
Torben
Reply all
Reply to author
Forward
0 new messages