The CreatorCon Call for Content is officially open! Get started here.

Constantine Kr1
Giga Guru

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:

find_real_file.png

 

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: 

find_real_file.png

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
*/
Comments
Mariappan Athi1
Tera Explorer

how to convert these day and month format in caps eg JAN and not jan

Constantine Kr1
Giga Guru

 how to convert these day and month format in caps eg JAN and not jan

For this question, I would recommend using the JavaScript  .toUpperCase() function. 

Example: 

gs.info( gd.getByFormat("MMM").toUpperCase( ) );
Version history
Last update:
‎03-24-2019 05:07 PM
Updated by: