views:

292

answers:

6

Is it possible on a web server to determine the users local time and timezone when they sent the request?

Could it be done using javascript to capture it and post it back to the server?

My company want to track how many users use our site outside of office hours (no I dont really know why either!).

Thanks.

+6  A: 

You need to put the client's JavaScript time into a hidden field, and assume their clock is set properly.

myTime = new Date() >> Tue Feb 03 2009 12:24:28 GMT-0500 (Eastern Standard Time)
Diodeus
Beat me to the punch :)
Miyagi Coder
You also have to assume that they haven't disabled Javascript...
Graeme Perrow
+2  A: 

You could load a date into a hidden field using JavaScript:

var newDate = new Date();
hiddenFieldName.value = newDate.toLocaleString();

Then on the postback to the sever grab that field.

Miyagi Coder
Do yourself a favor and use newDate.toUTCString() instead. toLocaleString gives you a string in the users language.
some
+1  A: 

JavaScript is indeed the way to go.

Fortunately the web has lots of sample code you can use. This page seems pretty comprehensive.

It should be noted that knowing someone's current offset is not the same as knowing their time zone, but it's probably enough for your purposes :)

Jon Skeet
A: 

Well you could read the browser's local time with JavaScript:

var now = new Date();

Then you could post it to the server using XmlHttpRequest or a hidden form field...

Ferdinand Beyer
+1  A: 

Certainly you could embed a JS derived client timestamp and send it back appended to some other request, but it's completely unreliable since the user could set their client time to anything they want, and it requires that second request which could be slightly abusive, or technically awkward to ensure. A lot of implementations will do this by fire-and-forgetting an AJAX request for a text file, or adding a single blank pixel image to the page.

You could try and derive a similar metric based on first requests and geolocating an IP - location and GMT timestamp giving you a local time - but that might be expensive if you haven't got an IP/Geo database already :)

annakata
Thats a good point about the postback, unless I use AJAX it won't work for initial requests.
Si Keep
and it won't work at all for noscripts
annakata
+1  A: 

You should consider reverse DNS resolution of your existing web server logs. You can then use geocoding to guess user's time zone (and their local time relative to your web server's time).

You would not need to write new JavaScript code, write custom server-side code to log user times, and then deploy an updated website.

This Perl script might be a helpful example: Perl Script that Does Bulk Reverse-DNS Lookups

cpeterso