Saturday, November 15, 2008

UTC and Atomic Time

In this special double issue, I'm going to show you how to obtain time values in the GMT timezone, as well as ultra-precise atomic clock time values.


Our PHP programmer friends have a slight advantage against us. Their language is aware of what time zone the server is located in and is capable of doing various things with that information, including returning time values without any timezone offset. ASP has no clue what time zone the server is set for, but we can use XMLHTTP to retrieve a time value from a NIST time server.


ASP

  1. function utcnow()
  2.     dim xmlhttp
  3.     dim response
  4.     ' Server to query datetime from
  5.     Const TimeServer = "http://time.nist.gov:13"
  6.     ' Use XML HTTP object to request web page content
  7.     Set xmlhttp = Server.CreateObject("Microsoft.XMLHTTP")
  8.     xmlhttp.Open "GET", TimeServer, false, "", ""
  9.     xmlhttp.Send
  10.     response = xmlhttp.ResponseText
  11.     set xmlhttp = nothing
  12.     ' Parse UTC date
  13.     utcnow = cDate(mid(response, 11, 2) & "/" & mid(response, 14, 2) & "/" & mid(response, 8, 2) & " " & mid(response, 16, 9))
  14. end function

If you were to compare the value returned by this function and the value returned by the built-in Now() function, you might notice more than just the hour value is different. This could mean you live in one of those funky half-hour-offset timezones, or it could mean that your server's clock is off by a few minutes. If accurate time values are important to you, you need a better Now() function. We can build one on top of the UTCnow() function we just wrote.


ASP

  1. function atomicnow()
  2.     dim utc
  3.     dim offset
  4.     utc = utcnow()
  5.     ' The order of the dates is important here!
  6.     offset = DateDiff("h", utc, now())
  7.     atomicnow = DateAdd("h", offset, utc)
  8. end function

There is expected to be some lag caused by this function, but the order of magnitude should only be milliseconds.


View implementation on Snipplr

No comments: