From: Colin Bartlett Date: 2010-01-24T00:11:58+09:00 Subject: Re: Get time object from the web? On Sat, Jan 23, 2010 at 12:34 AM, Jose Wong wrote: > Great! It seems to work, but, can someone help me for making a class > with that code, that will return that time object? Like this: > @now = ServerTime.get_time > @now is now the time object returned by that server... The following seems to work, but it *isn't* "production code" because it doesn't deal with timeouts or other failures, which should perhaps return nil or raise an exception. # based on code at http://juretta.com/log/2006/08/26/ruby_contacting_a_timeserver/ require "net/telnet" class ServerTime attr_reader :host TIME_SERVER = 'ntp2.fau.de' # 25567 = 70 * 365 + 70.div(4); this is *not* a general formula # for converting periods of years to seconds: leap years need # careful handling; also this ignores leap seconds. SECONDS_1900_01_01_TO_1970_01_01 = 25567 * 24 * 60 * 60 def initialize( host_v = nil ) @host = host_v || TIME_SERVER @options = { "Host" => @host, "Telnetmode" => false, "Timeout" => 30, "Port" => "time" } end # Note that this does *not* deal with what happens if there is a timeout # or other failure to get the time from the time server. def 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 Time.at( seconds - SECONDS_1900_01_01_TO_1970_01_01 ) end end st = ServerTime.new t = st.time puts "Time from #{st.host} -> #{t}" sleep 3 puts "Time from #{st.host} -> #{st.time}"