- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 02-08-2021 02:37 PM
Let's say you want to set a date field in a client-side script based on some serialized data (perhaps from a GlideAjax response)... wouldn't it be nice if you could just use a unix timestamp and only bother with converting it into the correct user-specific format once it's client-side? Here's a working client-side function that will do exactly that:
function timestampToDateString(timestamp){
return (new GwtDate(timestamp)).serializeInUserFormat();
}
It's that simple! GwtDate is a ServiceNow class available in most client contexts and it is fully aware of the user's configured timezone and preferred date format. Here's a fuller example demonstrating how to take a timestamp and set a DateTime field to that value:
function timestampToDateString(timestamp){
return (new GwtDate(timestamp)).serializeInUserFormat();
}
var myTimestamp = 161281910; // Usually this will come from somewhere else, like Ajax
// Set the field called date_time_field to match myTimestamp
g_form.setValue('date_time_field', timeStampToDateString(myTimestamp));
The above code should work for setting Date, Time, and DateTime fields.
A word of warning: duration fields break the rules when it comes to timezone handling. Unlike the other fields that accept a date string, duration fields always want a UTC time string, regardless of the user's local timezone. This means you will need to factor in the user's timezone and offset the timestamp before processing it. Here's a modified version of the prior function that does this:
function timestampToDurationString(timestamp){
return (new GwtDate(timestamp - g_tz_offset)).serializeInUserFormat();
}
One last caveat: GwtDate expects a seconds-based timestamp, but the server-side functions that create timestamps (GlideElement.dateNumericValue() and GlideDateTime.getNumericValue()) all produce timestamps based on milliseconds. If you use these to produce timestamps, don't forget to divide them by 1000 prior to sending them to the client via Ajax:
var gdt = new GlideDateTime();
// Calling getNumericValue yields a timestamp with the wrong units
gdt.getNumericValue(); // Yields 1612823323563, which is in milliseconds
// Dividing by 10000 yields a seconds timestamp which we can actually use client-side
// Rounding up to avoid any edge-cases where non-whole timestamps would be unexpected
Math.ceil(gdt.getNumericValue() / 1000) // Yields 1612823323
