Skip to content
Advertisement

Google Analytics Event Datetime

I have the javascript code below to trigger an event each time a visitor is clicking on a specific element on the page.

<script>
 var trackerName = ga.getAll()[0].get('name');
            
 ga(trackerName + '.send', 'event', {
  eventCategory: 'Product',
  eventAction: 'Outbound click',
  eventLabel: '<?php echo str_replace("'"," ",$product->pro_label_fr); ?>',
  eventValue: <?php echo intval($product->pro_price * 100); ?>,
  dimension1: '<?php echo Utils::getClientIp(); ?>',
  dimension2: '<?php echo $customer->cus_label; ?>',
  dimension3: '<?php echo date('m/d/Y h:i:s a', time()); ?>',
  dimension4: '<?php echo $category; ?>',
  dimension5: '1',
  dimension6: 'top',
  transport: 'beacon'
});
</script>

The problem is with the datetime (dimension3), because it’s in PHP I only get the time of when the page was loaded and not the time of the click.

Any idea how I could get the time of the click?

Thank you

Advertisement

Answer

PHP is processed before the page is created, so of course it is static. If you want a dynamic time, use JavaScript. But as JS is executed by the client, it will also use the client’s timezone, so you will have to recalculate it to the timezone you are expecting.

Create a method that returns the date string you need

<script>
    function getCurrentTime() {
        // create a ne (local) date object
        var date = new Date();
        // convert it to UTC
        var utcDate = new Date(date.toUTCString());
        // add/substract the hours from your preferred timezone. f.ex. -8 for PDT
        utcDate.setHours(utcDate.getHours() - 8);
        // create a new date object for PDT
        var myDate = new Date(utcDate);
        // return it in the US default format
        return pstDate.toLocaleString('en-US');
    }

    ga(trackerName + '.send', 'event', {
        // settings
        dimension3: getCurrentTime(),
        // other settings
    }
</script>

That should solve it from a technical point of view. But WHY are you doing this? Google Analytics automatically logs the event time for you, you don’t need to add it as a dimension.

On a side note: Be careful with logging IP addresses. In many countries, including the EU, this is illegal.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement