2 December 2013

Google Analytics: Tracking Visit Time

 

In a separate article I discussed how to compare time-related data to determine correlation.

I thought it might be helpful to include a method for recording the server time to the visit using a custom variable.

I have used PHP as the server code in this example, and the Async version of the GA tracking code.

In PHP:

// Set timestap for Analytics 
  $ga_timestamp = date("Hi");

// Write Google Analytics code, and insert timestamp

echo "
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-Y']);
  _gaq.push(['_setCustomVar', 1, 'Visit Timestamp', '$ga_timestamp', 2]);
  _gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

";

Here are the important notes…

$ga_timestamp = date("Hi");

This line sets a variable with the time in the format “hhmm”; for example, “0155” for five to two in the morning.

  _gaq.push(['_setAccount', 'UA-XXXXXXXX-Y']);

Remember to use your own UA tracking-ID.

  _gaq.push(['_setCustomVar', 1, 'Visit Timestamp', '$ga_timestamp', 2]);

This line sets the custom variable in slot 1. If you already use slot 1, adjust this line to record to a different slot. The variable we store has a session scope, i.e. it is set for the whole visit.

If you find this useful ,please remember to share the blog post and spread the love 🙂

EDIT:

Phil from our development team has kindly dotNetified this for me into a similar script. This C# script writes the total seconds since midnight on 1st Jan, 1970 as the timestamp.

@functions {
  public double ConvertNowToUnixTimestamp()
  {
      DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
      TimeSpan diff = DateTime.Now - origin;
      return Math.Floor(diff.TotalSeconds);
  }
}
 
<script type="javascript/text">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-Y']);
  _gaq.push(['_setCustomVar', 1, 'Visit Timestamp', '@ConvertNowToUnixTimestamp()', 2]);
  _gaq.push(['_trackPageview']);
 
(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

Search

Categories

Archives

Subscribe to Email Updates

Subscribe
 
  • Akash Agarwal

    Nice topic and very useful too. It’s also very important to tracking the time with the place of visitors. Thanks for sharing.

We are a digital transformation consultancy. We help our clients succeed.

View Services