6

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"?

  • Is parsing the output an option? I mean, if you have your system's time and the offset from the ntp server time, it should be relatively easy to combine the 2 and infer the ntp server's time. – terdon Dec 4 '12 at 15:42
  • How? My awk skills are rusty... – Zac B Dec 4 '12 at 15:48
  • I don't have ntpdate on my system, if you post the output, maybe I or someone else can figure it out. – terdon Dec 4 '12 at 15:56
  • similar question: superuser.com/questions/155772/… – golimar May 9 '13 at 13:39
2

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
  • 1
    Not sure if this actually works. I set my system time to be several hours off, but ntpdate printed offset -0.000033 sec. Perhaps something using ntpdate -d and looking at reference time is more useful? – Mikel May 16 '15 at 19:29

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.