logo

NJP

Formatting Date/Time values in ServiceNow Scripts

Import · Mar 24, 2019 · article

Many of ServiceNow's date/time classes inherit the Java class "SimpleDateFormat". Due to this, we can use the formatters available for this class to format how data is displayed in a ServiceNow script. This article was written as a quick reference / cheat sheet of examples compiled within the ServiceNow platform.

Some of the classes that use the getByFormat() method.

The full Java SimpleDateFormat documentation can be found here:

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Cheat Sheet:

image

Years

//Example date: March 31, 2019
var gd = new GlideDate();
gs.info(gd.getByFormat("yy"));
gs.info(gd.getByFormat("yyyy"));
gs.info(gd.getByFormat("yyyy-G"));
gs.info(gd.getByFormat("yyyy G"));

//Output:
*** Script: 19
*** Script: 2019
*** Script: 2019-AD
*** Script: 2019 AD

Months

var gd = new GlideDate();
gs.info(gd.getByFormat("M"));
gs.info(gd.getByFormat("MM"));
gs.info(gd.getByFormat("MMM"));
gs.info(gd.getByFormat("MMMM"));

//Output:
*** Script: 3
*** Script: 03
*** Script: Mar
*** Script: March

Weeks:

image

var gd = new GlideDate();
gs.info(gd.getByFormat("W"));  //Upper Case W (Week in Month)
gs.info(gd.getByFormat("WW")); //Upper Case W (Week in Month)
gs.info(gd.getByFormat("w"));  //Lower Case w (week in Year)

/* Output:  (See screenshot for explanation)
*** Script: 6
*** Script: 06
*** Script: 13
*/

Days

var gd = new GlideDate();
gs.info(gd.getByFormat("E"));
gs.info(gd.getByFormat("EEEE"));
gs.info(gd.getByFormat("dd"));   //Lowercase D (Day in Month)
gs.info(gd.getByFormat("u"));    //Day number of week (Monday = 1, Sunday = 7)


/*Output:
*** Script: Sun
*** Script: Sunday
*** Script: 31
*** Script: 7
*/

Hours / Minutes / Seconds

var gd = new GlideDate();

gs.info(gd.getByFormat("hh-mm-ss:SSS a z"));

gs.info(gd.getByFormat("a"));
gs.info(gd.getByFormat("hh"));
gs.info(gd.getByFormat("HH"));
gs.info(gd.getByFormat("mm"));   
gs.info(gd.getByFormat("ss"));
gs.info(gd.getByFormat("SSS"));
gs.info(gd.getByFormat("z"));    //Lowercase z
gs.info(gd.getByFormat("zzzzz"); //Lowercase z
gs.info(gd.getByFormat("Z"));    //Uppercase Z


/*Output:
*** Script: 09-26-03:724 PM UTC

*** Script: PM
*** Script: 09
*** Script: 21
*** Script: 26
*** Script: 03
*** Script: 724
*** Script: UTC
*** Script: Coordinated Universal Time
*** Script: +0000
*/

Labels:

image

View original source

https://www.servicenow.com/community/developer-articles/formatting-date-time-values-in-servicenow-scripts/ta-p/2328095