convert NTP time to Human-readable time

Oded picture Oded · Jul 29, 2010 · Viewed 10.9k times · Source

i have managed to make a NTP request and retrieve the server time from it's NTP response. i want to convert this number to a Human-readable time, writing in C++. can some one help me ? as example you can look at: http://www.4webhelp.net/us/timestamp.php?action=stamp&stamp=771554255&timezone=0 once you set the timestamp to 771554255 you'll get "29/7/2010 13:14:32". i wanna do the same in my code, any help ?

Answer

NinjaCat picture NinjaCat · Jul 29, 2010

It's not C++, but here's a perl implementation. Converting this into C++ should be no big deal:

http://www.ntp.org/ntpfaq/NTP-s-related.htm#AEN6780

# usage: perl n2u.pl timestamp
# timestamp is either decimal: [0-9]+.?[0-9]*
# or hex: (0x)?[0-9]+.?(0x)?[0-9]*

# Seconds between 1900-01-01 and 1970-01-01
my $NTP2UNIX = (70 * 365 + 17) * 86400;

my $timestamp = shift;
die "Usage perl n2u.pl timestamp (with or without decimals)\n"
    unless ($timestamp ne "");

my ($i, $f) = split(/\./, $timestamp, 2);
$f ||= 0;
if ($i =~ /^0x/) {
    $i = oct($i);
    $f = ($f =~ /^0x/) ? oct($f) / 2 ** 32 : "0.$f";
} else {
    $i = int($i);
    $f = $timestamp - $i;
}

my $t = $i - $NTP2UNIX;
while ($t < 0) {
    $t += 65536.0 * 65536.0;
}

my ($year, $mon, $day, $h, $m, $s) = (gmtime($t))[5, 4, 3, 2, 1, 0];
$s += $f;

printf("%d-%02d-%02d %02d:%02d:%06.3f\n",
       $year + 1900, $mon+1, $day, $h, $m, $s);