benclock

Anytime I have to deal with time, date, or timestamp string format conversions my brain shudders and I silently grown from within. It is not that it is over hard or technical, it just boils down to being outright tedious at times (no pun intended).

I recently had to generate an ISO-8601 timestamp string. I knew I had done it before and I had to search through my various note repositories before I found the code snippets that I had saved in a forward thinking manner for future use. I decided I had better just put the code snippet public so that it would be easy for me or other people to find it in the future.

The purpose of the ISO-8601 standard is to provide an unambiguous and well-defined way of identifying dates and times in a common format that helps avoid misinterpretation of numeric representations for the date/time combo. This is especially helpful when data is transferred between countries with different conventions for representing time stamps.

Sample ISO-8601 timestamps look like some of the following examples:

  • 2013-08-13T12:12-0600
  • 2003-07-16T01:24:32+0300

While I don’t know of an easy ServiceNow API function call that generates the current timestamp in ISO 8601 format, we have access to Java JDK libraries that give us this functionality in any of our ServiceNow scripts.

The following is a sample function and library that generates the current time in ISO-8601 format:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var SimpleDateFormat = Packages.java.text.SimpleDateFormat;
var TimeZone = Packages.java.util.TimeZone;
var Date = Packages.java.util.Date;

function isoNow(tz){
  var date = new Date();
  gs.print(date);
  var format = "yyyy-MM-dd'T'HH:mm:ssZ";
  var tz = TimeZone.getTimeZone(tz);
  var f = new SimpleDateFormat(format);
  f.setTimeZone(tz);
  return f.format(date);
}
gs.log(isoNow("US/Mountain"));

That snippet of code will take a date of “Wed Aug 14 12:05:36 MDT 2013” and convert it to “2013-08-14T12:05:36-0600”.

Passing in an empty string or not string at all to “isoNow” will return the timestamp with the UTC time zone (zulu time).

Update: 5 August 2017

With the Java code restrictions put on ServiceNow instances over the past several years, this method will likely no longer work.

Happily though, there is a much easier way. Essentially, covert the GlideDateTime object to Millisecond format and then use the newer Javascript call to convert it to an ISO 8601 string. Here is a sample code snippet:

1
2
3
var d = new GlideDateTime();
var ms = d.getNumericValue();
gs.info(new Date(ms).toISOString())

This will output:

2017-08-05T12:30:46.155Z