如何在不本地设置的情况下根据 NTP 服务器获取当前日期?

Zac*_*c B 6 linux centos date time-zone ntp

我想根据远程 NTP 服务器使用 Linux 获取当前日期和时间。我不想因此改变当地时间;我只想得到远程日期,根据本地时区调整,打印出来。返回的日期必须符合以下标准:

  1. 它需要相当准确。
  2. 它需要针对发出请求的本地系统上的时区进行调整。
  3. 它需要以易于阅读或可解释的方式进行格式化(标准日期格式,或自纪元以来的秒数)。

我试过的:

我可以调用ntpdate -q my.ntp.server并获取本地时间和服务器时间之间的偏移量,但这不会根据 NTP 服务器返回日期;它只返回偏移量和本地日期。

是否有一些简单的方法/命令我可以用来说:“根据给定的 NTP 服务器打印日期,根据我当前的时区进行调整”?

ter*_*don 2

这个 Perl 脚本应该可以满足您的需要(假设您不需要精确到 10 -6秒):

#!/usr/bin/perl -w

use strict;
use Math::Round;

## Get current date (epoch)
my $date=time();

## Get the seconds offset, rounding to the nearest second
my $ntp=nearest(0.1,`ntpdate -q $ARGV[0] | gawk '(\$NF~/sec/){print \$(NF-1)}'`); 

## Get the server's time
my $ntp_date=$date+$ntp;

## Convert to human readable and print
print "The time according to server $ARGV[0] is " . localtime($ntp_date) . "\n";
Run Code Online (Sandbox Code Playgroud)

将脚本保存为 check_ntp.pl 并使用服务器作为参数运行它:

perl ./check_ntp.pl my.ntp.server
Run Code Online (Sandbox Code Playgroud)