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

AkshatRastogi
Mega Guru

Hi,

 

Just add the line in bold:

 

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;
var dt = new GlideDateTime(userDateFormat);

gs.print(dt)
 

Hi @AkshatRastogi 
I just noticed that in output month is August, not September (2018-09-18T06:39:51Z')
Do you know why?
background script output:

2018-08-18 06:39:51

 

@miro2 

getUTCMonth  returns month  from 0 to  11   not 1 to 12.

add 1 month atfer getUTCMonth.

 

Please mark my answer as correct and helpful based on Impact.

Thanks for clarification