Computing Timezone difference from GMT in ASP VBScript

If you want to be nice to your web visitors, you will eventually have to start considering the "last-modified" HTTP headers in order to make sure that:
  • the browsers always get the most accurate data and
  • the dial-up users don't wait for data they have already cached.

Before getting there, you'll hit a major obstacle - all HTTP timestamps are in GMT (and in an obscure format, on top of that) and the time you get with the now() function is local to your timezone. No big deal in most languages - you just use system calls or DLLs to figure out the difference between local time and GMT ... but you can't do that in ASP. Writing a custom COM module is always an option if you own the web server (in which case you can hardcode the timezone offset anyway), but for those of us who rely on hosting (and distributing code), things get almost impossibly complex.

But, as always, there is a trick - using the XMLHTTPRequest object, the ASP script can execute a request on its own server (http://127.0.0.1) and compare the GMT timestamp in the reply with the current time to get the local timezone difference.

Here is the code to do it:

'
' FromHTTPDate - helper function that converts HTTP date
' into a date value
'
Function FromHTTPDate (SDate)
Dim n,LC,S
n=InStr(1,SDate,";",vbTextCompare)
If (n>0) Then
S = Left(SDate,n-5)
Else
If SDate > "9" Then S = Left(SDate,Len(SDate) - 4)
End If
n=InStr(1,S," ",vbTextCompare)
If (n>0) Then S = Mid(S,n+1,Len(S))
LC = Response.LCID : Response.LCID = 1033
FromHTTPDate=CDate(S) : Response.LCID = LC
End Function

'
' GetTimezoneDifference - returns hourly difference between
' local time and GMT
'
Function GetTimezoneDifference
Dim TZD
TZD = Application ("TimezoneDifference") ' reuse the result
If TypeName(TZD) = "Integer" Then ' if available
GetTimezoneDifference = TZD : Exit Function
End If

Dim HttpReq,Port,URL,RDT

Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
Port = Request.ServerVariables("SERVER_PORT")
URL = "http://127.0.0.1" & ":" & Port & "/"
HttpReq.open "GET", URL , False
HttpReq.send

RDT = FromHTTPDate(HttpReq.getResponseHeader("Date"))
TZD = CInt((Now() - RDT) * 24 + 0.05)
Application ("TimezoneDifference") = TZD ' cache the result
GetTimezoneDifference = TZD
End Function

1 comment:

Chris Bloom said...

Thanks for the tip. I'll be sure to add a link to this article in the comments of my DateOutput for ASP function for anyone that wants to incorporate it into their copy of the function.

Thanks again!

Post a Comment