How can I get the 2 digit day from a GlideDate in a workflow script?

gjz
Mega Sage

I've been struggling with this for quite awhile and I haven't seen a solution on the community that works for me.

 

I have a catalog item with a date variable.  In the workflow, I need to parse the month and day from the date, but the month and day needs to be two digits.  How can I script that?

 

Example:

2024-01-02 (YYYY-MM-DD)  is the variable's value.  I need the value 0102 in my script, not 12.

1 ACCEPTED SOLUTION

BalaG
Kilo Sage

Hello @gjz  you can use the slice string function as follows

var gdt = new GlideDateTime('2024-01-02 12:00:00' );
gs.print(('00'+ gdt.getMonth()).slice(-2) + ('00'+ gdt.getDayOfMonth()).slice(-2));

output -- 0102

 

Hope that helps

--

Bala Guthy

Please mark this as helpful or a solution as appropriate

View solution in original post

7 REPLIES 7

Elijah Aromola
Mega Sage

You can use getMonth() and getDay() to get these values.

var gdt = new GlideDateTime();
gs.print(gdt.getMonth());

var gdt2 = new GlideDateTime();
gs.print(gdt2.getDayOfMonth());

 

Sorry Elijah, but your answer does not address my question.  I asked how to get the dates and make them 2 digits.  There are two issues with your solution - both functions only return 1 digit if the number is less than 10 and both functions convert the date to the previous day and doesn't retain local time.

Tai Vu
Kilo Patron
Kilo Patron

Hi @gjz 

Have you considered splitting it to retrieve the full day part? Alternatively, you can concatenate '0' to the day part returned from getDayOfMonth if it's less than 10.

 

Cheers,

Tai Vu

RAMANA MURTHY G
Mega Sage
Mega Sage

Hello @gjz ,

 

find below background script, it may help you

var gdt = new GlideDateTime('02-04-2023');
var date = gdt.getMonth();
if(date<10){
    date = "0"+date;
}
gs.info(date);

var month = gdt.getDayOfMonth() + 1;
if(month<10){
    month = "0"+month;
}
gs.info(month);

var totalDate = date+month
gs.info(totalDate);

 

Please mark my answer correct & helpful, if it helps you

Thank you

 

 

Please mark my answer helpful  & correct if it helps you
Thank you

G Ramana Murthy
ServiceNow Developer