Skip to content

Instantly share code, notes, and snippets.

@seungjin
Created December 26, 2011 02:40
Show Gist options
  • Save seungjin/1520433 to your computer and use it in GitHub Desktop.
Save seungjin/1520433 to your computer and use it in GitHub Desktop.
check_time_sync.rb
def check_time_sync
require 'net/telnet'
time_server = 'time.bora.net'
options = {
"Host" => time_server,
"Telnetmode" => false,
"Timeout" => 30,
"Port" => "time"
}
# The time is the number of seconds since 00:00 (midnight) 1 January 1900
# GMT, such that the time 1 is 12:00:01 am on 1 January 1900 GMT; this
# base will serve until the year 2036.
seconds = Net::Telnet.new(options).recv(4).unpack('N').first
# The Ruby Time class handles dates with an epoch
# starting at midnight january 1 1970
# We have to use the Date class to work with pre-epoch dates.
require 'date'
def get_seconds_diff_1970_1900
# you might want to cache the Cache result... it won't change ;-)
(DateTime.new(1970, 1, 1) - DateTime.new(1900, 1, 1)).to_i * 24 * 60 * 60
end
# Convert seconds to a Time object
remote_time = Time.at(seconds - get_seconds_diff_1970_1900).strftime("%Y-%m-%d %H:%M:%S")
#puts "Time from #{time_server} -> #{remote_time}"
local_time = Time.now.strftime("%Y-%m-%d %H:%M:%S")
#puts "Time from local machine -> #{local_time}"
if (Time.at(seconds - get_seconds_diff_1970_1900).to_i - Time.now.to_i) == 0
return true
else
return (Time.at(seconds - get_seconds_diff_1970_1900).to_i - Time.now.to_i)
end
end
# test
puts check_time_sync()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment