将 NTP 时间转换为人类可读的时间

Ode*_*ded 5 c++ linux protocols ntp

我已成功发出 NTP 请求并从 NTP 响应中检索服务器时间。我想将这个数字转换为人类可读的时间,用 C++ 编写。有人能帮我吗 ?例如,您可以查看: http://www.4webhelp.net/us/timestamp.php ?action=stamp&stamp=771554255&timezone=0 一旦您将时间戳设置为 771554255,您将得到“29/7/2010 13:14 :32”。我想在我的代码中做同样的事情,有什么帮助吗?

Nin*_*Cat 3

它不是 C++,但这是一个 perl 实现。将其转换为 C++ 应该没什么大不了的:

http://www.ntp.org/ntpfaq/NTP-s-lated.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);
Run Code Online (Sandbox Code Playgroud)