Why GlideDateTime doesn't works in object?

Fabrizio Joaqui
Mega Guru

i tried to take this date, but GlideDateTime doesn't works inside Object:

var gdt = new GlideDateTime("2011-08-31 08:00:00");
var date = gdt.getDate()
gs.info(date)

var obj = {};

obj.date = new GlideDateTime("2011-08-31 08:00:00");
gs.info(JSON.stringify(obj));

//Output

/*
*** Script: 2011-08-31
*** Script: {"date":{}}
*/

how can i fix this?

1 ACCEPTED SOLUTION

Fabrizio Joaqui
Mega Guru

i solved it like this:

 

obj.date = new GlideDateTime("2011-08-31 08:00:00").getDate().toString();

 

View solution in original post

3 REPLIES 3

Fabrizio Joaqui
Mega Guru

i solved it like this:

 

obj.date = new GlideDateTime("2011-08-31 08:00:00").getDate().toString();

 

Gunjan Kiratkar
Kilo Patron
Kilo Patron

Hi @Fabrizio Joaqui ,

 

You are correct that the GlideDateTime class does not work inside objects. This is because the GlideDateTime class is not a plain JavaScript object and does not have the ability to be serialized into a JSON string.

One way to work around this issue is to store the string representation of the GlideDateTime object in the object. Here's an example of how you can do this:

var gdt = new GlideDateTime("2011-08-31 08:00:00");
var date = gdt.getValue();

var obj = {};
obj.date = date;
gs.info(JSON.stringify(obj));

 

Output :-

GunjanKiratkar_0-1673883426424.png

 


Please Mark My Response as Correct/Helpful based on Impact
Regards,
Gunjan Kiratkar
2X ServiceNow MVP
Community Rising Star 2022
Youtube : ServiceNow Guy

Sagar Pagar
Tera Patron

Hi @Fabrizio Joaqui,

 

Try this updated scripts -

 

var gdt = new GlideDateTime("2011-08-31 08:00:00");
var date = gdt.getDate()
gs.info(date)

var obj = {};

obj.date = new GlideDateTime("2011-08-31 08:00:00").toString();

gs.info(JSON.stringify(obj));

// Output -
// *** Script: 2011-08-31
// *** Script: {"date":"2011-08-31 08:00:00"}

 

Thanks,

Sagar Pagar

The world works with ServiceNow