You are currently viewing JavaScript Dates & ServiceNow

JavaScript Dates & ServiceNow

Hello ServiceNow Ninjas,

Javascript & ServiceNow scripting run hand in hand. We often use both in a mixed way such as using javascript API within Glide APIs or vice versa. And when it comes to dates I have faced a lot of confusion. 

In this article, I am providing a few basics of Javascript Dates that help in identifying, managing & using javascript date objects in a better way.

All below code snippets are tested in the background script.

Declare a new date object

var d = new Date();
*** Script: Thu Sep 08 2022 03:29:47 GMT-0700 (PDT)

You can Initialize the date as well

var d = new Date(2018, 11, 24, 10, 33, 30, 0);
*** Script: Mon Dec 24 2018 10:33:30 GMT-0800 (PST)

A date object can be created using “date strings” as well

var d = new Date("October 13, 2014 11:13:00");

*** Script: Mon Oct 13 2014 11:13:00 GMT-0700 (PDT)

How to parse date?

If you have a valid date string, you can use the Date. parse() method to convert it to milliseconds. Then milliseconds can be converted into a date object.

var d1 = Date.parse("March 21, 2012");
gs.print("Date1 - "+d1);
var d2 = new Date(d1);
gs.print("Date2 - "+d2);
*** Script: Date1 - 1332313200000
*** Script: Date2 - Wed Mar 21 2012 00:00:00 GMT-0700 (PDT)

Use the following methods to extract information from the date object:

getFullYear()Get the year as a four-digit number (yyyy)
getMonth()Get the month as a number (0-11)
getDate()Get the day as a number (1-31)
getHours()Get the hour (0-23)
getMinutes()Get the minute (0-59)
getSeconds()Get the second (0-59)
getMilliseconds()Get the millisecond (0-999)
getTime()Get the time (milliseconds since January 1, 1970)
getDay()Get the weekday as a number (0-6) the time. ECMAScript 5
var d = new Date();
*** Script: 2022
*** Script: 8
*** Script: 8
*** Script: 3

I hope this will help you get an edge over Javascript date objects and functions.


end footer

Leave a Reply