Calculate Future Date and Time for a calculation within a Scheduled Job script

jmiskey
Kilo Sage

I am trying to calculate a future date and time for a field that I need to populate in a script found within a Scheduled Job.  Basically, I need to go 3 days from the current date, and choose 5:00 AM that day.

 

So, if today is February 10, 2023, the dynamic date calculation should return February 13, 2023 5:00 AM.

 

I found the "gs.dayAgo" function, but that does not return time.

So if I try to use it like this:

gr.scheduled=gs.daysAgo(-3);

It returns February 13, 2023 12:00 AM instead of February 13, 2023 5:00 AM (right day, wrong time).

How can I get it to add the 5:00 AM time?

 

Thanks

 

1 ACCEPTED SOLUTION

Jamsta1912
Tera Guru

Hi, try this:

var dt = new GlideDate();
dt.addDays(3);

var dt2 = new GlideDateTime();
dt2.setValue(dt.getValue() + ' 05:00:00');
gr.scheduled = dt2;

View solution in original post

10 REPLIES 10

-O-
Kilo Patron
Kilo Patron

The code below should get you the desired date/time:

var runAtGDT = getRunAtGDT(new GlideDateTime());

function getRunAtGDT (gdt) {
	var tz = Packages.java.util.TimeZone.getTimeZone('<time zone name>');

	gdt.setTZ(tz);

	var today5AMLocalTime = getToday5AMLocalTime(gdt);
	
	return get3DaysLocalTimeFrom(today5AMLocalTime);
}

function get3DaysLocalTimeFrom (today5AM) {
	var gdt = new GlideDateTime(today5AM);

	gdt.addDays(3);
	return gdt;
}

function getToday5AMLocalTime (nowGDT) {
	var gdt = new GlideDateTime();
	var dateLocalTime = nowGDT.getDisplayValueInternal().substr(0, 10);

	gdt.setDisplayValueInternal(dateLocalTime + ' 05:00:00');
	return gdt;
}

gs.debug(runAtGDT.getValue());
gs.debug(runAtGDT.getDisplayValueInternal());

After running the code above runAtGDT will be a GlideDateTime that is 3 days from the moment of execution @ 5 AM in the morning.

If the scheduled script is executed in the context of a user that has the correct time zone configured, lines

	var tz = Packages.java.util.TimeZone.getTimeZone('<time zone name>');
	...
	gdt.setTZ(tz);

can be omitted.
If the script is executed with any other user (one that does not have the desired TZ selected in its profile, e.g. the system user), line

	var tz = Packages.java.util.TimeZone.getTimeZone('<time zone name>');

has to be modified to contain the desired TZ, e.g:

	var tz = Packages.java.util.TimeZone.getTimeZone('America/Chicago');