Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question
    
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

1 Answer 1

up vote 2 down vote accepted

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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