February 18, 2014, 9:13 am - James Farrer
TL;DR
I keep coming back to this post for specific tidbits so I decided I would put the key code snippet right at the top to make it easy. Basically, to get a javascript date from a ServiceNow date field value do this:
var date_number = getDateFromFormat(g_form.getValue('the_date_field'), g_user_date_format);
var my_date = new Date(date_number);
Or, from a Date/Time field do this:
var date_number = getDateFromFormat(g_form.getValue('the_date_time_field'), g_user_date_time_format); var my_date = new Date(date_number);
The Long Version
Working with dates on the client side of things in Service-Now has always been a challenge. Part of this is just due to Javascript and the challenges associated with dates and the other is ServiceNow. Given that users can have their own date format makes it even more challenging. That said, we are given some tools (albeit undocumented ones) that can help improve the situation.
I ran across some information (thanks to John Roberts) that helps the situation drastically. The key comes down to a couple global variables defined by the system and a function provided that helps use those variables.
The variables give us the date and datetime formats for the logged in user, and the function lets us use those to get something we can work with a little easier.
g_user_date_time_format
g_user_date_format
function isValidDateTime(value){ if(value == '' || value == undefined || value == null){ return false; } return(getDateFromFormat(value, g_user_date_time_format) != 0); }
function isValidDate(value){ if(value == '' || value == undefined || value == null){ return false; } return (getDateFromFormat(value, g_user_date_format) != 0); }
To take this a step further, you could easily add comparisons of dates or add custom date formats based on the values.
One thing to keep in mind with this, depending on where the date is coming from you may still have two date formats. Any of the dates that will work as shown are going to be the values in fields on a form or the Display Value of the date. If you're getting something from the server (e.g. via GlideAjax) as just a value then it will be stored in the regular system format of YYYY-MM-DD HH:MM:SS.
Hopefully this helps save you some of the frustration I've experienced over the years.