Skip to main content
  1. Blog Post/

Tip: Grabbing the visitor's first date from cookies using Google Tag Manager

2 min · 329 words
Table of Contents

With the new Universal Analytics cookies and everything being calculated server-side, it's more difficult to detect some attribution problems or verifying if they were already fixed.

For example after fixing a self-referrals problem we can continue getting more of them in our reports if some users were previusly tagged in Google Analytics.

One little trick we could use is to grab the cookie creation date from the "_ga" cookie, convert it to an understandable format like YYYYMMDD, and then use it a custom dimension in order to see if those self-referrals where created before fixing our site implementation.

Ok, I know we could directly segment those sessions by the "User Type" dimension but this way we could run some cool cohort analysis based on that data, for example days since an user landed on our site for first time to when he registered or performed any other action like buying something, signing up in our newsletter or whatever.

We're going to use a single Variable in Google Tag Manager to get this value, and then we could use it whenever we want, to directly send that date into a custom dimension or calculate any other dimension/metric

CODE

function(){
  var regex = new RegExp("_ga=([^;]+)");
  var value = regex.exec(document.cookie);
  var cookieCreationDate = (value != null) ? new Date(value[1].split('.')[3]*1000) : undefined;

  if(typeof(cookieCreationDate)!=="undefined")
  {

    var year = cookieCreationDate.getFullYear().toString();
    var month = (cookieCreationDate.getMonth()+1).toString();
    var day  = cookieCreationDate.getDate().toString();
    cookieCreationDate = year + (month[1]?month:"0"+month[0]) + (day[1]?day:"0"+day[0]);
  }
  
  return cookieCreationDate;
}