Inbound Email Action: Converting dates are returning undefined

mythNOW
Tera Expert

Hello ServiceNow community,

 

Currently, I am trying to convert a date from a subject email so that it reads correctly in the Change module Start date. The date in the email is structured as M/D/YYYY @ HH:MM PM/AM.  For my use case, I have been assigned to work on an existing script, and edited the script accordingly attempting so the date is formatted to match the Change Record start date (MM-DD-YYYY).  Yet when attempting to use padStart, and ensuring the values of month and day are string value, I receive an undefined result when looking at the message logs.  Here is the script:

 

// Extract Start Date/Time (the (.*?) grabs the date and time. Typical result is i.e 5/18/2024 @ 08:00 PM)
    var stReg = /Start Date\/Time:(.*?)End Date\/Time/gi;
    var startDateTime = stReg.exec(htmlcode)[1]; // Ensure there's a match
    var ogDateTime = startDateTime.trim(); // Clean up leading/trailing spaces
    gs.info('CDT extracted start date' + ogDateTime);

    // Split into date and time parts (split date and time as two elements)
    var startDateParts = ogDateTime.split(" @ ");
    gs.info('CDT split date/time:' + startDateParts);
    if (startDateParts.length !== 2) {
        gs.info("Error splitting date/time");
        return; // Exit if split fails
    }
    // Reformat date to MM-DD-YYYY
    var datepart1 = startDateParts[0].trim();
    gs.info('CDT date parts trimmed:' + datepart1);
    var dateComponents = datepart1.split("/");
    gs.info('CDT date parts split' + dateComponents); //Dates should split M,D,Y
    if (dateComponents.length !== 3) {
        gs.info("Error splitting date components");
        return; // Exit if split fails
    }
    var monthArray = dateComponents[0];
    gs.log('CDT start month' + monthArray);
    var monthString = String(monthArray);
    gs.info('CDT month string value ' + monthString);
    var paddedMonth = monthString.padStart(2, '0');
    gs.log('CDT start month padded ' + paddedMonth);
    var dayArray = dateComponents[1];
    var dayString = String(dayArray);
    var paddedDay = dayString.padStart(2, '0');
    gs.log('CDT start day padded ' + paddedDay);
    var year = dateComponents[2]; // Year should be 4 digits
    var formattedDate = [paddedMonth, paddedDay, year].join("-");
    gs.info("CDT formatted date:" + formattedDate);
 
When looking at the message logs for gs.info('CDT month string value ' + monthString); it reads 5 in this example. This is the desired result.  
mythNOW_0-1715192708253.png

 

But when using:

var paddedMonth = monthString.padStart(2, '0');

 

I am always receiving undefined.  I am hoping to achieve a result of "05".

mythNOW_1-1715192904212.png

 

 

Is there any type of correction I can make with my script? Thank you everyone.

0 REPLIES 0