Linux – How to get the current date according to an NTP server without setting it locally

centosdatelinuxntptime zone

I want to get the current date and time according to a remote NTP server, using Linux. I don't want to change the local time as a result; I just want to get the remote date, adjusted for the local time zone, printed out. The date returned must comply with the following criteria:

  1. It needs to be reasonably accurate.
  2. It needs to be adjusted for the timezone on the local system making the request.
  3. It needs to be formatted in an easily-readable or interpretable way (standard date format, or seconds since epoch).

What I've Tried:

I can call ntpdate -q my.ntp.server and get the offset between the local time and the server's time, but that doesn't return the date according to the NTP server; it just returns the offset and the local date.

Is there some easy way/command I can use to say: "Print out the date according to a given NTP server, adjusted for my current timezone"?

Best Answer

This Perl script should do what you need (assuming you don't need precision to the 10-6 of a second):

#!/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";

Save the script as check_ntp.pl and run it with the server as an argument:

perl ./check_ntp.pl my.ntp.server
Related Question