SK> another way:
SK>
http://juretta.com/log/2006/08/26/ruby_contacting_a_timeserver/
In that URL cited, there is a comment that reads
=A0# you might want to cache the Cache result... it won't change ;-)
What does this mean?
The code (full code is below for ease of reference) says that
the time server returns the number of seconds from 1900-01-01.
The Ruby Time class works with the number of seconds
from 1970-01-01, so to use the seconds to create a Time object
we need to adjust the seconds returned from the time server
by the number of seconds from 1900-01-01 to 1970-01-01.
That number of adjustment seconds won't change,
so once it has been calculated using get_seconds_diff_1970_1900
that adjustment can be stored for future use.
So you could do something like:
adjustment_secs_1900_to_1970 =3D get_seconds_diff_1970_1900
and then
seconds =3D Net::Telnet.new(options).recv(4).unpack('N').first
remote_time =3D Time.at( seconds - adjustment_secs_1900_to_1970 )
Does that explain what you were asking about?
## code at
http://juretta.com/log/2006/08/26/ruby_contacting_a_timeserver/
require 'net/telnet'
TIME_SERVER =3D 'ntp2.fau.de'
options =3D {
"Host" =3D> TIME_SERVER,
"Telnetmode" =3D> false,
"Timeout" =3D> 30,
"Port" =3D> "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 =3D 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 =3D Time.at(seconds - \
get_seconds_diff_1970_1900).strftime("%Y-%m-%d %H:%M:%S")
print "Time from #{TIME_SERVER} -> #{remote_time}"