Search code examples
javascripttagsgoogle-tag-manager

Convert console.log into return on script for GTM


I finally found a script that takes todays date, add 7 days and then outputs it in the format I need to put in GTM. But then I got the error from GTM that it needs a return.

As far as I have been able to find, this means that the Javascript should end with a "return". For example (random example): return daysOfWeek[time.getDay()];

The code I have now is:

var someDate = new Date();
var numberOfDaysToAdd = 7;
var result = someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
console.log(new Date(result).toLocaleDateString('en-CA'));

Can somebody explain how to convert this to something with a return at the end? Or perhaps in such a way that GTM accepts it?

As a novice/beginner is tried to simply add something like return newdate(new Date(result).toLocaleDateString('en-CA')); but that obviously didn't work. I also tried to add a function at the beginning, but that didn't work either. In the end I had to throw in the towel because I simply don't understand well enough how this part works.

I tried to edit the script, but my very limited knowledge on this part fails me. I was kinda hoping that it would be a simple case of changing the last part of the code. But that doesn't seem to work.

I am trying to achieve that GTM accepts the script and the output gives me the date 7 days from today, in the format "YYYY-MM-DD". Right now it is 2023-10-09, so the output would be: 2023-10-16.


Solution

  • (function () {
      var someDate = new Date();
      var numberOfDaysToAdd = 7;
      var result = someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
      return new Date(result).toLocaleDateString("en-CA");
    })();