The CreatorCon Call for Content is officially open! Get started here.

Compare two date/times

Community Alums
Not applicable

Hi everyone,

I have a date/time field called 'Follow Up'. I am setting a rule to block users from selecting a date/time further than 3 months in the future. How can I achieve this using a Business Rule? 

find_real_file.png

 

 

This BR script I have so far but not working, works on After Insert or Update:

var gr = new GlideRecord('incident');
gr.addQuery('sys_id','621ee25bdb917b00cbebaa805b9619d3');
gr.query();

if(gr.next()){

var gdt1 = gr.follow_up;

var time = new GlideDateTime(); // Without input sets it to current UTC.
var gdt2 = time.getDisplayValue(); //Gets the date and time value in the current user's display format and time zone.

var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2
gs.print(dur.getDisplayValue());

if (dur >= 90) {
    current.follow_up.setError("Data/time must be within next 3 months");
    current.setAbortAction(true);
}


}
1 ACCEPTED SOLUTION

Community Alums
Not applicable

Thanks everyone for the help.

I am sharing the final code which I tested and is working.

Basically it ensures no date/time further than 3 months in the future is selected and also no date/time in past is selected.

 I used a before insert and update Business Rule.

(function executeRule(current, previous /*null when async*/) {

//Script to ensure no date/time further than 3 months in the future is selected
var gdt1 = new GlideDateTime(current.follow_up);
var gdt2 = new GlideDateTime();
gdt2.addMonthsLocalTime(3);
	
if(gdt1.after(gdt2)) {  // Date time selected is after 3 months 
	gs.addErrorMessage("Follow up date/time cannot be after 3 months.");
	current.follow_up = previous.follow_up;
}

//Script to ensure no date/time in past is selected	
var currentDateTime = new GlideDateTime();	
if(gdt1.before(currentDateTime)) {    // Date time selected in past
	gs.addErrorMessage("Follow up date/time cannot be set in the past.");
	current.follow_up = previous.follow_up; 
}
	
})(current, previous);

View solution in original post

12 REPLIES 12

Lakshmi51
Giga Guru

var gdt = new GlideDateTime(gs.nowDateTime());
//gs.log(gdt);
var gdt1= new GlideDateTime(gdt);

gdt1.addMonths(3);
var gdt2 =this.getParameter('sysparm_start');
//gs.log(ed);
if (gdt2>gdt1) {

return 0;

} else {
return 1;
}
},

Community Alums
Not applicable

Thanks for you feedback 🙂

Lakshmi51
Giga Guru

Please mark helpful and mark answer correct

 

 

Thanks,

Lakshmi

 

dvp
Mega Sage

Try this script

var gdt = new GlideDateTime(gr.follow_up);
	
var cdt = new GlideDateTime();
cdt.addMonthsUTC(3);

var diff = gs.dateDiff(cdt, gdt, true);


if (diff > 0) {
    current.follow_up.setError("Data/time must be within next 3 months");
    current.setAbortAction(true);
}