From: Colin Bartlett Date: 2010-01-23T02:12:09+09:00 Subject: Re: Get time object from the web? On Fri, Jan 22, 2010 at 11:43 AM, Ralph Shnelvar wrote: > 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 >  # 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 = get_seconds_diff_1970_1900 and then seconds = Net::Telnet.new(options).recv(4).unpack('N').first remote_time = 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 = 'ntp2.fau.de' 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") print "Time from #{TIME_SERVER} -> #{remote_time}"