Today I hit a frustrating issue with a data import where a couple of fields which contained Unix date/time information were being received in scientific notation (e.g. 1.59855015616942E9). How do we turn this into something we can use in ServiceNow?
Requirements
- Convert a Unix Epoch timestamp, stored as number of seconds since 1970-01-01 00:00:00, in scientific 'e' notation (e.g. 1.59855015616942E9) into a GlideDateTime object containing the appropriate value (e.g. 2020-08-27 17:42:36).
Approach
Try not to tear out your hair figuring this one out!
Implementation
Make sure your number is actually a number (using the Number() function), then convert that into the number of milliseconds since the Unix epoch, then use the setValue() function on a GlideDateTime object to get a useful variable.
var evilNumber = '1.59855015616942E9'; var gdt = new GlideDateTime(); // Make sure evilNumber is actually a number by using JavaScript Number() function. // Then multiply it by 1000 because GlideDateTime setValue() function expects the number // of *milliseconds* from the Unix epoch, and ta-da! gdt.setValue(Number(evilNumber)*1000); // Print or otherwise use your shiny new GlideDateTime object: gs.print(gdt.toString());
Enhancements
Write yourself a nice script include and a function to wrap this, then you can use it more easily in the future, and forget the pain you went through to figure it out in the first place... :-)
Disclaimer
As always, please test and evaluate anything you find in the community before adopting it for your own use. Hope someone finds this useful, comments and suggestions welcome!
Comments
Post a Comment