Set Formats for DATE and TIME values including milli seconds

We always struggle with setting formats for Date and time values as getByFormat() is not available for GlideDateTime() function. We can use below method to

get local date and time with milli seconds in any format we want. Below code is to set the format – “yyyyMMdd HH24mmssSS”. Format can be changed as per requirements.

Getting the milliseconds value using GlideDate() as getLocalTime() doesn’t provide milliseconds value.

var gd = new GlideDate();

var currentdate = (gd.getByFormat(“HH:mm:ss:SS”)); // SS will give the milliseconds value

var value = currentdate.split(‘:’);

var msec = value[3];

var format = ‘yyyyMMdd HH24mmss’.split(‘ ‘);

var gdt = new GlideDateTime();

var formatDate = format[0];

var formatTime = format[1];

var gdate = gdt.getLocalDate().getByFormat(formatDate);

var gtime = gdt.getLocalTime().getByFormat(formatTime);

var output = gdate + ‘ ’+ gtime + msec;

This will provide the result: 20220708 17241530452