Subtract days from date/time field
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-31-2019 11:19 AM
I have a custom date/time field on one of the ci tables in servicenow. From a high level what I wanted to do is look at that date/time field and if it is x days or more from now then set the ci status to some value. What I was thinking is do a split on the date/time and just extract the date, then from there can I just subtract the number of days from that date?
Currently that date field on the ci just holds a value like this - "07/30/2019 00:32:34". Then I will use that in my glidequery to only update those records that are x days and older.
I have taken a look at glidedate but not sure my date is in the correct format to use for that, so thats why I was wondering if I can just subtract the days from the date string.
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-31-2019 11:31 AM
Below is the script which you can use to check the difference in seconds between <yourField> and current date.
var fieldDate = current.<yourField>;
var gdt = new GlideDateTime(fieldDate);
var curDate = new GlideDateTime();
var diffSeconds = gs.dateDiff(gdt.getDisplayValue(),curDate.getDisplayValue(), true)
if (diffSeconds > X*(24*60*60)) {
//Your update logic here
}
Hope this helps!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-01-2019 12:31 PM
Thanks thats useful. I realize now though that I need to take a date/time field, subtract x days from that, and then return a date/time field, to use in a gliderecord query, any idea how I would do that?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-01-2019 02:29 PM
Here is the script to get the date after subtracting 2 days. You can substitute 2 with X. Also replace <yourField> with your datetime field from which you want to subtract.
var fieldDate = current.<yourField>;
var gdt = new GlideDateTime(fieldDate);
gdt.addDays(-2); //Substitute 2 with X days
var dateBefore = gdt.getDate();
gs.print(dateBefore);
Hope this answers your question.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-01-2019 02:43 PM
Hi,
You can just do:
var gdt = new GlideDateTime(current.date_time_field);
gdt.addDays(-2);
then use gdt as needed.
Please mark reply as Helpful/Correct, if applicable. Thanks!
Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!