Analytics Log - Adil Khan

View Original

Adobe Launch & GTM: Custom JS To Calculate Age From a Timestamp

So, let’s say you have a user’s date of birth available as a timestamp in the dataLayer object but want to pass the age to Adobe Analytics as an eVar, which is the most common case.

Example date of birth in dataLayer var: Tue Oct 07 1975 00:00:00 GMT+0400 (Gulf Standard Time)

In order to know the age of the user, we need to go through the below steps:

  1. Extract 1975 from the dataLayer variable.

  2. Find out the current year [2020, in this case]

  3. Subtract 1975 from 2020

  4. Return the difference 45 as an integer

The wrong approach: In order to extract 1975, I first thought of checking JS methods to extract string ‘1975’ from the text using str.slice (11,15) << 11 being the starting character and 15 being ending character in the timestamp. Once extracted, convert the string “1975” to an integer, using getFullYear JS method to get 2020 and run the subtraction.

However, on trying the str.slice method, the JS wouldn’t work.

The right approach: On checking with our friendly dev, GK, he explained about Object datatype in JS. https://www.w3schools.com/js/js_object_definition.asp , which runs on key: value pairs with dates always being an object data type.

Meaning, that JS already understands the example timestamp: Tue Oct 07 1975 00:00:00 GMT+0400 (Gulf Standard Time) is made up of DDD MM DD YYYY HH:MM:SS in Gulf timezone.

Knowing this simplifies a lot of the steps, meaning that the Custom JS is much easier now.

How does this Custom JS work?

Var x = calling the existing dataLayer variable called' ‘dataLayer var: DOB’ that has the timestamp.

Var dobYear = getting the full year (YYYY) from var x.

You now have a new variable called curYear where you’re pulling the current year (2020).

Finally, a var called age that runs the subtraction from the two values, 2020 - 1975. Then, return the value of age var as an output to use in Adobe Launch.

See this content in the original post

The above method would work with both, GTM and Adobe Launch. It’s just a slightly different syntax when it comes to calling the DL val, GTM being more eaiser with {{var name}}. Here’s how the code would be in GTM:

See this content in the original post

That’s it. Once you have this Custom JS working in Adobe Cloud Debugger, you can include this Custom JS var in your eVar as a conversion dimension.

Hope you found this post helpful.

See this form in the original post