Tracking time of access with Google Analytics


by Ulf on January 21st, 2009 (Permalink)

A friend recently asked me if it was possible to use Google Analytics (GA) to report on the distribution of the hour of the day at which visitors drop by his web site. Nothing fine-grained, just a number from 0 to 23 along with the number of visits during that hour. Having recently read a blog post on how to use GA to detect the browser’s installed JRE version with some custom JavaScript, I figured this shouldn’t be too hard.

And it wasn’t – just two lines of JavaScript code will do the trick: first to create a Date object, and then to set a custom variable with the hours value using GA’s setVar call. Here’s the code in its entirety:

<script type="text/javascript">
    var pageTracker = _gat._getTracker("......");
    pageTracker._trackPageview();

    dt = new Date();
    pageTracker._setVar("hour: " + dt.getHours());
</script>

A day or so after adding this to your page you should start seeing entries like “hour: 8″, “hours: 17″ etc. under Visitors -> User Defined in your GA reports. That’s all there is to it. If you read the blog post linked above you’ll find mention of how to drill down into this data using GA’s Advanced Segments functionality as well.

If you’re just a bit proficient in JavaScript -particularly its Date object- then it’s easy to change the tracking timeframe from full hours to anything that’s convenient (maybe hour of the day combined with day of the week). You can also pick some other prefix than “hours: ” (but you should use some common prefix so that you can filter the list of user defined variables for just these.)

It really goes without saying, but since the time is recorded on the client, that’s the hour you’ll get in the reports – not the time on your server when the page was accessed. An important difference if your visitors are from timezones other than the one your server happens to be in!


One Response to “Tracking time of access with Google Analytics”

  1. Gili Says:

    I would suggest reading the second part of my post: http://cowwoc.blogspot.com/2008/12/tracking-java-versions-using-google.html

    “events” work better than “setVar” in my experience.

Leave a Reply