How to modify date format from mm/dd/yyyy to yyyy-mm-dd in onbefore transform script?

Rithu
Kilo Contributor

Hi,

 

Can i know how we can modify the date format from mm/dd/yyyy to yyyy-mm-dd in onbefore transform script. The target table has date field as a textbox. 

Thanks in advance.

 

7 REPLIES 7

Alexander Grisb
Kilo Guru

If you're trying to convert date format, you can go ahead and do a couple ways in order to solve it. You can use a regular expression to get the month, day and year, and rearrange it in the script. If that date format is in servicenow, you can use var gd = gr.datefield.getGlideObject(). GlideDate also has a method called getByFormat. I think the best way to do this is to get the month day and year and rearrange it if it's a transform script. As long as your data is sanitized, it should be fairly consistent. Theoretically, it would look something like this. I haven't tested it, but it should be something like this.

var date = "insertDateField here" + ""; // to string this
// the regex matches each of the slashes that are seperated, so its like this
// [month,day,year]
// updated with a better regex
var month = date.match(/([0-9].*)\/([0-9].*)\/([0-9].*)/)[1];
var day = date.match(/([0-9].*)\/([0-9].*)\/([0-9].*)/)[2];
var year = date.match(/([0-9].*)\/([0-9].*)\/([0-9].*)/)[3];
var newDate = year + "/" + month +"/"+day; 

 

Hope this answer helped or solved your problem. If so, please mark as 'Helpful' or 'Correct'. Thanks!

Alexander

To change the format to yyyy-mm-dd, should i give the below expression?

var newDate = year + "-" + month + "-" + day;

That's correct.

Chaitanya Redd5
Tera Guru

Hi,

You can use the below piece of code to format the date to yyyy-mm-dd.

var date= new GlideDate();//replace new GlideDate() with the incoming date
var date2 = date.getByFormat('yyyy/MM/dd');//now use the date2 to set the field value

Kindly mark my answer as Correct and Helpful based on the Impact.

Regards,

Chaitanya