Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to get previous month with year in server script

RK41
Tera Expert

Hi SNOW Community,

 

I need to print previous month with year value (YYYYMM) in custom field whenever user updates record. I will use BR for this modification. So anyone please suggest me a way to achieve it.

 

Ex: (Just have to get previous month with an year)

1. Consider today date is 09 Sep 2023, when user updates record, I want to print 202308 in custom text field.

2. For an example today date is 03 Jan 2024, when user updates record, I want to print 202312 in custom text field.

 

Thanks,

RK

1 ACCEPTED SOLUTION

Vishal Birajdar
Giga Sage

Hello @RK41 ,

 

Try below script in background script and check if its fulfill you need.

 

var d = "2024-01-12"

var date = new GlideDateTime(d);

date.addMonthsUTC(-1); // -1 will subtract one month from current date

gs.info("Previous Date=" + date);

// Split the date

var pDate = date.toString().split("-")[0] + date.toString().split("-")[1];

gs.info(pDate);

 

Output : 

VishalBirajdar7_0-1694156898999.png

 

 

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

View solution in original post

4 REPLIES 4

Vishal Birajdar
Giga Sage

Hello @RK41 ,

 

Try below script in background script and check if its fulfill you need.

 

var d = "2024-01-12"

var date = new GlideDateTime(d);

date.addMonthsUTC(-1); // -1 will subtract one month from current date

gs.info("Previous Date=" + date);

// Split the date

var pDate = date.toString().split("-")[0] + date.toString().split("-")[1];

gs.info(pDate);

 

Output : 

VishalBirajdar7_0-1694156898999.png

 

 

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

Thanks Vishal. I have tried the same way. Now its working as I expected.

 

var gdt = new GlideDateTime();
gdt.addMonthsLocalTime(-1);
var localDt = gdt.getLocalDate();

var name = localDt.toString().replace("-","");
var YM= name.slice(0, 6);
gs.info(YM);

Ankur Bawiskar
Tera Patron
Tera Patron

@RK41 

So please share what script did you try and what didn't work?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hi Ankur,

 

I got the solution and updated the script in previous reply. Thanks.