Converting a JavaScript Date to a ServiceNow Date/Time String

roy_scheer
ServiceNow Employee
ServiceNow Employee

I was recently working on a task where I needed to randomize dates in JavaScript and convert those JavaScript date objects into a format I could insert into a ServiceNow Date/Time Field. I wrote the function below which takes a JavaScript date object as it's input and returns an SNC Date/Time friendly output. I've also attached it in a file format.

function convertJavascriptDatetoSncDate(date){
var monthMap = new Object();
monthMap.Jan = '01';
monthMap.Feb = '02';
monthMap.Mar = '03';
monthMap.Apr = '04';
monthMap.May = '05';
monthMap.Jun = '06';
monthMap.Jul = '07';
monthMap.Aug = '08';
monthMap.Sep = '09';
monthMap.Oct = '10';
monthMap.Nov = '11';
monthMap.Dec = '12';

var matchDate = date.toString();

var match = matchDate.match(/^(\w+) (\w+) (\d+) (\d+) (\d+):(\d+):(\d+) /);
var sncDate = match[4] + '-' + monthMap[match[2]] + '-' + match[3] + ' ' + match[5] + ':' + match[6] + ':' + match[7];

return sncDate;
}

2 REPLIES 2

john_roberts
Mega Guru

Here's another randomizer if you need to work with GlideDateTime objects. I used this a lot for generating demo data since you can provide start and end parameters.
generateRandomDate.js


jamesmcwhinney
Giga Guru

I think this will fail if the user's ServiceNow preference is configured with a different date format.


I just ran into that issue attempting to do something similar.