How to convert the date/time format to MM/DD/YYYY HH:MM:SS?

Bird1
Mega Sage

Hello,

 

I need help. I tried to get the date/time data from a field in Change Request. I tried to use getDisplayValue before but the result is the date/time format is not stable. Sometimes got

1. MM/DD/YYYY HH:MM:SS or 

2. MM.DD.YYYY HH:MM:SS or 

3. MM-DD-YYYY HH:MM:SS

 

I assumed the unstable of DisplayValue because we received some record from POST API, they may use another format, so that cause of problem.

 

So, I switch using getValue instead but the format is not satisfied for user YYYY-MM-DD HH:MM:SS, so I tried to find out the solution to convert the date/time format from getValue (YYYY-MM-DD HH:MM:SS) to MM/DD/YYYY HH:MM:SS.

 

Sample Script:

var gr = new GlideRecord('change_request');
gr.addQuery('number', 'CHG0058582');
gr.query();

if (gr.next())

{

gs.print(gr.start_date.getValue());

}

 

 

Result: 

 2023-05-04 23:00:00

 

What I need result is 05/04/2023 23:00:00 (MM/DD/YYYY HH:MM:SS format).

1 ACCEPTED SOLUTION

Sagar Pagar
Tera Patron

Hello@Bird1,

 

Try this updated scripts. It will gives you date time in required format.

 

var chgRecord = new GlideRecord('change_request');
chgRecord.addQuery('number', 'CHG0058582');
chgRecord.query();
if (chgRecord.next()) {

	var start_date = chgRecord.start_date.getValue();
	gs.info("start_date: " + start_date);

	var today = new GlideDateTime(start_date);
	var day = today.getDayOfMonthUTC();
	var month = today.getMonthLocalTime();
	var year = today.getYearLocalTime();
	var time = today.getTime();
	var timeCreated = time.getByFormat('HH:mm:ss');

	// Set the date format
	var requiredDate = day + '/' + month + '/' + year + " " + timeCreated;
	gs.info('requiredDate: ' + requiredDate);
}

 

 

If my response helps to solve your issue. Kindly mark it as helpful & correct. It will be helpful for future readers.
Thanks,
Sagar Pagar

 

The world works with ServiceNow

View solution in original post

5 REPLIES 5

Shiva Beemani
Tera Contributor

Hi

 

Please use this script.

 
var gr = new GlideRecord('change_request');
gr.addQuery('number', 'CHG0040007');
gr.query();

if (gr.next()) {
    var startDate = gr.start_date.getValue(); // Get the date/time in YYYY-MM-DD HH:MM:SS format

    // Parse the date using GlideDateTime
    var gdt = new GlideDateTime(startDate);
    var day =gdt.getDayOfMonthUTC();
    var month=gdt.getMonthLocalTime();
    var year=gdt.getYearLocalTime();
        var timezoneoffset = new Date().getTimezoneOffset();
        var time = new Date(timezoneoffset*60*1000);
        var formattedTime = time.toLocaleTimeString('en-US');
       
   
    gs.info(day+"/"+month+"/"+year+" "+formattedTime);
}