How to select n-months ahead/ago from current month while querying custom table and adding options to select box?

hyperjam
Giga Contributor

On Catalog Item Form i have Select Box variable and adding options to that select box using onLoad() Client script.

PICTURE_2.png

function onLoad() {

//var currentDate = new Date();

//var getcurrentmonth = currentDate.getMonth()+1;

var gp = new GlideRecord('u_month_year');

gp.orderByDesc('u_month_year');

gp.query();

while(gp.next()){

g_form.addOption('month_report_test',gp.u_display_month_year, gp.u_display_month_year);

}}}

This is table from which i query options   (particularly from column 2). 2-nd column - String field [u_display_month_year] is the result of Business rule running on the 1st column - Date field [u_month_year].

PICTURE_3.png

However, in my Select Box on the form, i need to give user option only to select 3 month ahead/ago + current month. How to achieve this?

i.e.

Sep

Oct

Nov

Dec - current month

Jan

Feb

Mar

3 REPLIES 3

Abhinay Erra
Giga Sage

Dealing with dates on the client side is tricky. Use GlideAjax to query the the month year table and add 3 months to the current date and get those months and pass it to the client side.


Examples of asynchronous GlideAjax


HV1
Mega Guru

Try below:




function onLoad() {


        var today = new Date();


        var gp = new GlideRecord('u_month_year');


        gp.orderByDesc('u_month_year');


        gp.query();


        while(gp.next()){


                  var dt = new Date(gp.<the date field from u_month_year table displayed in screenshot>);


                  if(differenceInMonths(dt, today) == 3 || differenceInMonths(dt, today) == 0) {


                            g_form.addOption('month_report_test',gp.u_display_month_year, gp.u_display_month_year);


                  }


        }


}



function differenceInMonths(start, end){


  return Math.round(Math.abs(start.getMonth() - end.getMonth() + (12 * (start.getFullYear() - end.getFullYear()))));


}


FYI:   This will not give you consistent results. There can be time zone conversion issues on client side.