How To Add Days To A Date With GlideDateTime() and addDays()

How To Add Days To A Date Scripting with time in ServiceNow can keep you up at night. It can be tricky, difficult to get things to work, and there doesn’t seem to be great …

use addDays() to add or remove days

Buy The "ServiceNow Developer's Manual" Now

We've packed over a decade of ServiceNow Development advice, into a single e-book.

Buy It Now
Stripe Climate Badge

The Snowball will contribute 5% of your purchase to remove CO₂ from the atmosphere.

How To Add Days To A Date

Scripting with time in ServiceNow can keep you up at night.

It can be tricky, difficult to get things to work, and there doesn’t seem to be great documentation on things related to time.

When you have access to the GlideDateTime object(), there are a bunch of different ways that you can work with this object to do whatever you need to do.

You essentially just create the GlideDateTimeObject(), by storing it in a variable. And then you can access methods off of this, in this situation being addDays().

You can either add or remove days to a date, using our example below.

To remove days from a current date, you can just pass in a negative number, which will subtract days from the GlideDateTime() object.

There are countless scenarios where you’ll find yourself wanting to add or remove days from a GlideDateTime() object.

NOTE: Also be aware that this is all on the server. So this will only work in Business Rules and Script Include. There is a completely different way to use this on the client side.

This will not work with a client script or on the Service Portal.

Adding Days With addDays()

Let’s see it in use.

Here is how you’d add 2 weeks to a GlideDateTime object.

var gdt = new GlideDateTime();
gdt.addDays(14); // adds 14 days to the current date
gs.print(gdt);

This will return the following:

2023-01-04 01:37:50

It’s as simple as that, just a couple of lines of code.

Removing Days With addDays()

Alternatively, here is how you’d remove 7 days from a GlideDateTime object.

You just pass in a negative number as a parameter, as shown below.

var gdt = new GlideDateTime();
gdt.addDays(-7); // removes 7 days from the current date
gs.print(gdt);

This will return the following:

2022-12-14 01:46:33

Hopefully you’ve found this helpful.

Let us know if you have seen any different or better uses of addDays().



What Do You Think About This Article?

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Product Image

Jeffrey just purchased A ServiceNow Developer’s Manual 15 Minutes ago from Boston MA.

Buy Now
0
Would love your thoughts, please comment.x
()
x