How to convert the field sys_created_on to UNIX time.

Alon Grod
Tera Expert

Hi,

I created PUT rest message and I need to pass some parameters to the json. one of the parameters is the field sys_created_on of tyep Date/Time on the incident table.
When Im trying to test the REST Message Im getting error saying:
"Expected unix time" regarding the value of sys_created_on that im passing.
How can I convert this field's value to UNIX time?

1 ACCEPTED SOLUTION

Community Alums
Not applicable

In ServiceNow, you can convert a Date/Time field to UNIX time (also known as Epoch time) using the GlideDateTime class.

Here's an example of how you can convert the sys_created_on field to UNIX time:

 

// Assume incidentGR is a GlideRecord on the incident table
var sysCreatedOn = incidentGR.getValue('sys_created_on');

// Create a GlideDateTime object
var gdt = new GlideDateTime(sysCreatedOn);

// Get the UNIX timestamp
var unixTime = gdt.getNumericValue();

// Now, you can pass unixTime to your REST message

 

In this script, getNumericValue() method returns the number of milliseconds since January 1, 1970 00:00:00 GMT. This is the UNIX timestamp, but in milliseconds.

If the API expects the UNIX timestamp in seconds, simply divide the result by 1000:

View solution in original post

6 REPLIES 6

Pratiksha2
Mega Sage

Hello @Alon Grod ,

To convert a Date/Time field to UNIX time ( Epoch time) using the GlideDateTime class you can refer below code:

 

 

 var incident = new GlideRecord('incident');
incident.get('sys_id', '//incident_sys_id');
var unixTime = new GlideDateTime(incident.getValue('sys_created_on')).getNumericValue();

 

 

Please Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks,

Pratiksha

Samiksha Gunjat
Kilo Guru

Hi @Alon Grod ,

In ServiceNow, you can convert a date/time field value to UNIX time using a GlideDateTime object. You can use its getNumericValue() method to convert a date/time value to UNIX time.

 

// Get the incident record
var incident = new GlideRecord('incident');
incident.get('sys_id', '<incident_sys_id>'); // Replace <incident_sys_id> with the actual sys_id of the incident

// Get the sys_created_on value
var sysCreatedOn = incident.getValue('sys_created_on');

// Convert sys_created_on to UNIX time
var dateTime = new GlideDateTime(sysCreatedOn);
var unixTime = dateTime.getNumericValue();

gs.info('UNIX Time: ' + unixTime);

 

Please mark this comment as Correct Answer/Helpful if it helped you. 

Regards,

Samiksha Gunjate