Transform date from ISO 8601 format to yyyy-MM-dd HH:mm:ss ?

miro2
Mega Sage

Hi,

 

I have a question about converting the date from ISO 8601 format to yyyy-MM-dd HH:mm:ss 

I use this script in background script from community but I'm getting as an output 

2018-8-18 6:39:51

 How to modify script to get default ServiceNow format yyyy-MM-dd HH:mm:ss (for example 2018-09-18 06:39:51)

 

var source_iso = '2018-09-18T06:39:51Z'; 
if(source_iso.indexOf(".")==-1) 
{
  source_iso =source_iso.replace("Z", ".000Z");
}

var d = new Date(source_iso);
var day= d.getUTCDate();
var month=d.getUTCMonth();
var year=d.getUTCFullYear();
var hours=d.getUTCHours();
var minutes=d.getUTCMinutes();
var seconds=d.getUTCSeconds();

var userDateFormat = year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
gs.info(userDateFormat)

 

 

1 ACCEPTED SOLUTION

Johns Marokky
Tera Guru

Hi @miro2 ,

I am not good with the ISO 8601 time format however I came up with one code which will help in converting the date to the ServiceNow standard format.

Please try the code below.

var source_iso = '2018-09-18T06:39:51Z'; 
source_iso = source_iso.replace("T"," ");
var gdt = new GlideDateTime(source_iso);
gs.info(gdt);

if the source_iso will be in the same format every time we can use this code.

Try this and let me know if it works out for you.

 

Mark Helpful and Accept the solution if it helps in solving your Problem.

 

Regards,

Johns

View solution in original post

11 REPLIES 11

Hi @miro2 ,

i think in the function Date. getUTCMonth() gives the value from 0 to 11. Like if the date is Jan it will result as 0. So in general we need to add 1 to the getUTCMonth() result.

i hope this helps in your query.

 

Mark helpful if it helps in solving your problem.

 

Regards,

Johns

Samuel O_Connel
Tera Contributor

I understand that has been resolved, but I wrote a more dynamic function that will convert. 

ISO8601 strings of various formats from YYYY-MM-DDTHH:MMZ to YYYY-MM-DDTHH:MM:SS.sssZ
var input = ["2016-04-02T05:50:06.103Z","2015-07-12T15:24:46Z","2018-12-18T15:54Z"];
input.forEach(function(time){
	gs.info(convertISO8601(time));
});

function convertISO8601(time) {
    var dateTimeArr = time.split("T");
    var dateString = dateTimeArr[0];
	var timeString = dateTimeArr[1];
	var ms = parseInt(timeString.substring(timeString.indexOf('.')+1,timeString.indexOf('Z')));
    var utcTimeString = dateString + " " +timeString.substring(0, timeString.indexOf("."));
    var gdt = new GlideDateTime(utcTimeString);
	gdt.add(ms);
	return gdt;
}