I'm trying to create a dateAdd function in SSJS by calling the dateAdd function in Ampscript. The code below works. But I cannot figure out how to make the date argument dynamic. This means the function in my code always starts with the current date time and calculates a new date from there. I would like to make the function truly dynamic by passing a date to the function.
My problem is that the date in SSJS and Ampscript is not formatted in the same way. That is a problem when I pass the date into the ampscript code.
I'm aware of this question (Date manipulation Function SSJS) regarding creating a dateadd function in SSJS, but the answer there takes another approach. It tries to make the dateadd function from scratch in Javascript. I want to take advantage of the function that is already made in Ampscript.
<!-- For debugging only start -->
<p>
Printing a date in ampscript for comparison<br>
newDateAmpScript: %%=v(NOW())=%% <br><br>
</p>
<!-- For debugging only end -->
<script runat="server">
Platform.Load("Core","1.1.1");
// For debugging only start
var newDateSsjs = new Date();
Write('Printing a date in Javascript for comparison<br>')
Write('newDateSsjs: ' + newDateSsjs + "<br><br>");
// For debugging only end
function dateAdd(date, intervalNumber, intervalUnit) {
var calulatedDateAmpScriptString = '%' + '%['
+ 'VAR @calulatedDate '
+ 'SET @calulatedDate = SystemDateToLocalDate(DateAdd(NOW(), ' + intervalNumber +', "' + intervalUnit + '")) '
+ 'VAR @calulatedDateIso '
+ 'SET @calulatedDateIso = FormatDate(@calulatedDate, "iso") '
+ ']%' + '%';
// Printing ampscript string for easier debugging
Write(calulatedDateAmpScriptString + "<br><br>");
try {
var content = Platform.Function.TreatAsContent(calulatedDateAmpScriptString);
return Platform.Variable.GetValue("@calulatedDateIso");
}
catch(e) {
Write("error: " + Stringify(e) + "<br><br>")
}
}
// Calling the dateAdd function to test it
var modifiedDateFrom = dateAdd(newDateSsjs, -18, 'D');
Write("modifiedDateFrom: " + modifiedDateFrom);
</script>